Search code examples
powershellget-childitem

Powershell -- Get-ChildItem Directory full path and lastaccesstime


I am attempting to output full directory path and lastaccesstime in one line.

Needed -- R:\Directory1\Directory2\Directory3, March 10, 1015

What I am getting -- R:\Directory1\Directory2\Directory3

March 10, 1015

Here is my code, It isn't that complicated, but it is beyond me.

Get-ChildItem -Path "R:\" -Directory | foreach-object -process{$_.FullName, $_.LastAccessTime} | Where{ $_.LastAccessTime -lt [datetime]::Today.AddYears(-2) } | Out-File c:\temp\test.csv

I have used foreach-object in the past in order to ensure I do not truncate the excessively long directory names and paths, but never used it when pulling two properties. I would like the information to be on all one line, but haven't been successful. Thanks in advance for the assist.


Solution

  • I recommend filtering (Where-Object) before selecting the properties you want. Also I think you want to replace ForEach-Object with Select-Object, and lastly I think you want Export-Csv rather than Out-File. Example:

    Get-ChildItem -Path "R:\" -Directory |
      Where-Object { $_.LastAccessTime -lt [DateTime]::Today.AddYears(-2) } |
      Select-Object FullName,LastAccessTime |
      Export-Csv C:\temp\test.csv -NoTypeInformation