powershellfileproperties-file

PowerShell Get All Files in Folder Tree LastAccessed and export to csv


I have a Powershell Script that I am using to try to Get ALL Files in a Folder Tree that were LastAccessedTime > 365 days ago. I know my script is using Plus 10 days - but that is for testing purposes as I have just created files to test this with.

$Folder = 'D:\Temp\*.*'
$lastAccessDate = (Get-Date).AddDays(10)

Get-ChildItem $Folder -Recurse | Where-Object {
    $_.LastAccessTime -lt $lastAccessDate
} | Select-Object -ExpandProperty Name, LastAccessTime | 
 Export-CSV "C:\Temp\FileListing.csv" -NoTypeInformation -Encoding UTF8

I have Also tried this code based on this link Learn PowerShell

Get-ChildItem $Folder -Recurse | Where-Object {
    $_.LastAccessTime -lt $lastAccessDate
} | Select-Object -ExpandProperty Expand - Property Name, LastAccessTime | 
 Export-CSV "C:\Temp\FileListing.csv" -NoTypeInformation -Encoding UTF8

Error on the first code

Select-Object : Cannot convert 'System.Object[]' to the type 'System.String' required 
by parameter 'ExpandProperty'. Specified method is not supported.

Error on this

Get-ChildItem $Folder -Recurse | Where-Object {
    $_.LastAccessTime -lt $lastAccessDate
} | Select-Object -ExpandProperty Name,LastAccessTime | 
 Export-CSV "C:\Temp\FileListing.csv" -NoTypeInformation -Encoding UTF8
Select-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ExpandProperty'. Specified method is not supported.
At line:8 char:35
+ } | Select-Object -ExpandProperty Name,LastAccessTime |
+                                   ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.SelectObjectCommand

Solution

  • You just need to remove Expand from your code, like so:

    $Folder = 'D:\Temp\*.*'
    $lastAccessDate = (Get-Date).AddDays(10)
    
    Get-ChildItem $Folder -Recurse | Where-Object {
        $_.LastAccessTime -lt $lastAccessDate
    } | Select-Object -Property Name, LastAccessTime | 
     Export-CSV "C:\Temp\FileListing.csv" -NoTypeInformation -Encoding UTF8
    

    The first error says that Name cannot be expanded since it's a string, not an object that contains properties. Select-Object -Property selects the given properties of the object(s) comming down the pipe, Select-Object -ExpandProperty selects the properties of the given objects of the object(s) comming down the pipe.