简体   繁体   中英

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" (eg, abc_3.dat) and copy the data to abc.dat. Similarly for xyz and pqr. These files will keep on being added.

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM