drgreenthumb93
drgreenthumb93

Reputation: 1

Need to list all new files in directory with Powershell

I have to create a list of all latest or accessed files in a directory in .csv format. However my current script doesn't output a useful file. (always 0KB)

Get-ChildItem -Path X:\ -Directory -Recurse -ErrorAction SilentlyContinue | 
ForEach-Object { Get-ChildItem $_.Name -Recurse | 
select Name, *time | 
Sort-Object -Property LastAccessTime -Descending | 
Select-Object -First 1 } |
Export-Csv -Path C:\...\testfile.csv

Does anyone have a better idea?

EDIT: The errors look like this:

+ CategoryInfo          : ReadError: (X:\xxx:String) [Get-ChildItem], DirectoryNotFoundException
    + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

Upvotes: 0

Views: 396

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5227

That code might generate some errors if you don't cd to X:\ before running it. You can remediate that with changing:

# this
Get-ChildItem $_.Name -Recurse
# to this
Get-ChildItem $_.FullName -Recurse

Then it always uses absolute path rather than relative one.


NOTE: as @mklement0 pointed out in the comments, it's worth noting that in PowerShell 6 and higher the same can be achieved by using the object directly (no need to use .FullName property).

Here's his helpful answer explaining it in details - really worth reading!

Upvotes: 1

Related Questions