Powershell – Find Most Recent 12 Files from Folder Pattern

My disk folder structure is like this:

D:\Application\DEV
D:\Application\DEV\Cust1
D:\Application\DEV\Cust1\Archive
D:\Application\DEV\Cust1\Archive\210
D:\Application\DEV\Cust1\Archive\204
D:\Application\DEV\Cust1\Inbound
D:\Application\DEV\Cust1\Inbound\204
D:\Application\DEV\Cust1\Inbound\210
D:\Application\DEV\Cust1\Outbound
D:\Application\DEV\Cust1\Outbound\204
D:\Application\DEV\Cust1\Outbound\210
Similar for \Cust2
Similar for \Cust3 etc

I was looking for a sample 210 EDI Invoice to use in testing; and I wanted the most recent ones.

It turns out you can put a wildcard in the variable passed on the -Path parameter. In that case, I don’t really need the -Recurse option, but I included it anyway (just in case someone created additional subfolders).

<pre>
cls 
$Startpath = "D:\Application\DEV\*\Outbound\210"

#If you just want THE Most Recent File: 
#$latest = Get-ChildItem -Recurse -Path $Startpath | Sort-Object LastAccessTime -Descending | Select-Object -First 1 
#Write-Host "Latest= $($lastest.Fullname)" 

#Most recent 12 files (or whatever number you chose in the -First ## parameter) 
$latestFiles = Get-ChildItem -Recurse -Path $Startpath | Sort-Object LastAccessTime -Descending | Select-Object -First 12
Write-Host "Outbound Latest 12 files" 
foreach ($file in $latestFiles) 
{
   Write-Host $file.FullName
}
</pre>

Use the .FullName property to show the complete folder name in the results.

Uncategorized  

Leave a Reply