mrfreester
mrfreester

Reputation: 1991

PowerShell script to select some files in a directory

Right now I have a script that will get the last five files in a directory. It looks like this:

$diffs = Get-ChildItem "C:\usr\local\work\tnl\Database\ReleaseScripts" -Filter "*.sql" | Sort-Object Name -Descending | Select-Object -first 5 | Sort-Object Name

I need to have it select all of the last files starting with a certain one. For example, if the files were named

201.txt
202.txt
203.txt
204.txt
up to
210.txt

I might need to select all the files starting with 203.txt to the end of the list.

I could get the file name of the one I'm looking for and use that in the script. I'm just not familiar with what scripting tools I have to do that. Is there a way to edit my line to get it to do that in just one line, or will I have to put it in a loop to get my results?

Upvotes: 3

Views: 18157

Answers (1)

rerun
rerun

Reputation: 25505

This is works but needs to be expanded if you file name structure is any more complex or there is a chance your original filter would grab non conforming file names.

$diffs = Get-ChildItem "C:\usr\local\work\tnl\Database\ReleaseScripts" -Filter "*.sql" |?
{[Int][System.Text.RegularExpressions.Regex]::match($_.name,"\d+").Value -gt 201 }| 
Sort-Object Name -Descending | Select-Object -first 5 | Sort-Object Name

Upvotes: 4

Related Questions