2

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.

boxdog
  • 7,894
  • 2
  • 18
  • 27
  • Please [format your code and sample input/output properly](http://meta.stackexchange.com/a/22189/248777). – mklement0 Mar 27 '19 at 01:53

2 Answers2

1

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
}
Esperento57
  • 16,521
  • 3
  • 39
  • 45
0
  • 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