Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to select some files in a directory

Tags:

powershell

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?

like image 273
mrfreester Avatar asked Mar 08 '26 02:03

mrfreester


1 Answers

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
like image 151
rerun Avatar answered Mar 10 '26 16:03

rerun