简体   繁体   中英

PowerShell command to get a file that has the highest number in the filename string

I'm new to PowerShell. I have files in a folder with one-up numbers. I'm trying to find the file with the highest number and change that name.

I'm able to return the file with the following command:

Get-ChildItem -Path C:\Temp\Wayne\Folder1\File*.txt |
    Sort-Object |
        Select-Object -Last 1 -ExpandProperty Name

it returns:

Get-ChildItem -Path C:\Temp\Wayne\Folder2\File*.txt |
    Sort-Object |
        Select-Object -Last 1 -ExpandProperty Name

PS C:\> File0005.txt

I would like to change File0005.txt , to FileCHANGED(TodaysDate).txt , then move it to C:\\Temp\\Wayne\\Folder1\\File*.txt

I'm able to return the correct file, but before I can get to the point of moving it, I'm stuck at trying to rename it.

try this :

Get-ChildItem "C:\Temp\File*.txt" | sort Name -Descending | select -First 1 | %{

$Newname="{0:yyyy-MM-dd-HH-mm-ss-fffff}({1:yyyy-MM-dd-HH-mm-ss-fffff})" -f $_.LastWriteTime,  (Get-Date)
Rename-Item $_.FullName -NewName $Newname
}
  • Your (by default alphabetically) sorting approach only works with numbers of equal length.
  • more universal is using $ToNatural by Roman Kuzmin which prepends all numbers with zeroes to a unique length

On my empty Ramdrive A:\\ the following script:

## Q:\Test\2019\03\27\SO_55368572.ps1
$SrcDir = 'A:\Folder1'  # 'C:\Temp\Wayne\Folder1'
$DstDir = 'A:\Folder2'  # 'C:\Temp\Wayne\Folder2'

## create test folders,files
MD $SrcDir,$DstDir | Out-Null
1..5|New-Item -ItemType File -Path {"{0}\File{1:D4}.txt" -f $SrcDir,$_}|Out-Null

"_"*10+" Before "+"_"*10
Tree A:\ /F

Get-ChildItem -Path $SrcDir -Filter File*.txt |
  Sort-Object | Select-Object -Last 1 |
    Move-Item -Destination {Join-Path $DstDir (
      "FileChanged({0:yyyy-MM-dd}){1}" -f (Get-Date),$_.Extension)}

"_"*10+" After "+"_"*10
Tree A:\ /F

Tree A:\ /F

yields this (German locale) output:

> Q:\Test\2019\03\27\SO_55368572.ps1
__________ Before __________
Auflistung der Ordnerpfade für Volume RamDisk
Volumeseriennummer : 5566-7788
A:\
├───Folder1
│       File0001.txt
│       File0002.txt
│       File0003.txt
│       File0004.txt
│       File0005.txt
│
└───Folder2
__________ After __________
Auflistung der Ordnerpfade für Volume RamDisk
Volumeseriennummer : 5566-7788
A:\
├───Folder1
│       File0001.txt
│       File0002.txt
│       File0003.txt
│       File0004.txt
│
└───Folder2
        FileChanged(2019-03-27).txt

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