Home > OS >  How to get Folder stats to a csv file for a specific year (like 2022)
How to get Folder stats to a csv file for a specific year (like 2022)

Time:10-15

This script runs fine but I don't know how to add something like to get just 2022 last edited files only like {where LastWriteTime -eq 2022}

$arr = @()
gci 'C:\Users\myusername\Documents\' -recurse  | ? {$_.PSIsContainer -eq $False} | % {
  $obj = New-Object PSObject
  $obj | Add-Member NoteProperty Directory $_.DirectoryName
  $obj | Add-Member NoteProperty Name $_.Name
  $obj | Add-Member NoteProperty Length $_.Length
  $obj | Add-Member NoteProperty CreationTime $_.CreationTime
  $obj | Add-Member NoteProperty Access $_.LastAccessTime
  $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)
  $arr  = $obj
  }
  $arr | Export-CSV -notypeinformation "C:\Users\myusername\Downloads\report.csv"

CodePudding user response:

LastWriteTime is a DateTime instance, hence you can simply check the Year property and compare against it. As for your code, 3 recommendations:

  1. Use -File or -Directory when needing to filter by any of them.
  2. Use PSCustomObject to instantiate your objects. It's easier and faster.
  3. Avoid adding elements = to a fixed collection @(). You can take full advantage of the pipeline in this case, get the files one by one, process each object and output them to a file.
Get-ChildItem 'C:\Users\myusername\Documents\' -Recurse -File | ForEach-Object {
    if($_.LastWriteTime.Year -eq 2022) {
        [pscustomobject]@{
            Directory    = $_.DirectoryName
            Name         = $_.Name
            Length       = $_.Length
            CreationTime = $_.CreationTime
            Access       = $_.LastAccessTime
            Owner        = (Get-ACL $_.FullName).Owner
        }
    }
} | Export-CSV "C:\Users\myusername\Downloads\report.csv" -NoTypeInformation

CodePudding user response:

Santiago's helpful answer contains an effective solution and explains the problems with your approach well.

Let me complement it with an alternative solution that uses the Where-Object cmdlet to perform the desired filtering first, and the Select-Object cmdlet with calculated properties to get the desired property names and values to pass to Export-Csv:

Get-ChildItem -File C:\Users\myusername\Documents -recurse  | 
  Where-Object { $_.LastWriteTime.Year -eq 2022 } |
  Select-Object @{ Name='Directory'; Expression = { $_.DirectoryName } },
                Name,
                Length,
                CreationTime,
                @{ Name='Access'; Expression = { $_.LastAccessTime } },
                @{ Name='Owner'; Expression = { (Get-ACL $_.FullName).Owner } } |
  Export-CSV -notypeinformation "C:\Users\myusername\Downloads\report.csv"
  • Related