I am writing a script that will rename all files in a folder to a given name (param) with in increasing counter. I want the counter to print with 3 digits (001, 002, etc). My code looks like it would work but it tells me that all my files don't exist. I also cant figure out the 3 digits correctly. Any help is appreciated!
param( [string]$NAME, [string]$FOLDER ) $NAME = "SEATTLE" $FOLDER = "C:\Users\user00\Documents\Datasheets" $files = Get-ChildItem -Path $FOLDER -Recurse $counter = 001 foreach ($file in $files){ Rename-Item $file.Name -NewName $NAME $counter++ } 02 Answers
This is what padding is used for. This is a common thing to do and well documented in many places.
Just doing a search for your use case, will return many examples.
$i = 1 Dir xyz* | Rename-Item –NewName {$_.name –replace "0101",("01{0:D2}" -f $script:i++)} Format Leading Zeros in PowerShell
# Examples: "{0:0000}" -f 4 # Results 0004 "{0:0000}" -f 45 # Results 0045 "{0:0000}" -f 456 # Results 0456 "{0:0000}" -f 4567 # Results 4567 1..10 | foreach { $i="{0:0000}" -f $_ $dir="c:\test\Target_$i" $file="file_$i.txt" $target=Join-Path -Path $dir -ChildPath $file Write-Host "Updating $target" } # Results <# Updating c:\test\Target_0001\file_0001.txt Updating c:\test\Target_0002\file_0002.txt Updating c:\test\Target_0003\file_0003.txt Updating c:\test\Target_0004\file_0004.txt Updating c:\test\Target_0005\file_0005.txt Updating c:\test\Target_0006\file_0006.txt Updating c:\test\Target_0007\file_0007.txt Updating c:\test\Target_0008\file_0008.txt Updating c:\test\Target_0009\file_0009.txt Updating c:\test\Target_0010\file_0010.txt #> $NAME = "SEATTLE" $FOLDER = "C:\Users\user00\Documents\Datasheets" [ref]$i = 1 GEt-ChildItem -Path $FOLDER -File -Recurse | Rename-Item -NewName {'{0}{1:d3}{2}' -f $NAME, $i.value++, $_.Extension} The format operator (-f) constructs the new mane from your base name: {0}=$NAME, the counter padded to 3 places: {1:d3}=$i.Value, and the extension of the file being renamed: {2}=$_.Extension
$i must be cast as [ref] and referenced as $i.Value in order to be incremented from within the scope of the script block.