user1438511
user1438511

Reputation: 21

Selecting latest file from a folder and copy it to another file using powershell script

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

Answers (1)

Aaron Jensen
Aaron Jensen

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

Related Questions