Reputation: 21
I am new to powershell scripts and need some help.
We have a folder \Output
. It will have the files in following format :
abc_1.dat
abc_2.dat
xyz_1.dat
abc_3.dat
pqr_2.dat
......
Now I want to find the latest file starting with "abc" (e.g., abc_3.dat) and copy the data to abc.dat. Similarly for xyz and pqr. These files will keep on being added.
Upvotes: 2
Views: 2509
Reputation: 26729
First, you need to find your list of unique prefixes:
$prefixes = Get-ChildItem \Output |
Where-Object { -not $_.PsIsContainer } |
Foreach-Object { $_.Name.Substring(0, 3) } |
Select-Object -Unique
Then, for each prefix, find the latest/highest number and copy it to the preferred file:
$latest = $prefixes |
Foreach-Object {
Join-Path \Output "$_*" |
Get-ChildItem |
Add-Member NoteProperty -Name ID -Value { [int] ($_.BaseName -split '_')[1] } -PassThru |
Sort-Object ID -Descending |
Select-Object -First |
Copy-Item -Destination \Output\$_.dat
}
Upvotes: 1