Home > Software engineering >  How can I use powershell to rename files with padded zeros
How can I use powershell to rename files with padded zeros

Time:10-23

I need to limit the files affected to Example*.pdf. The files have 1-3 digits in the names and I need to standardize them. So Example_1.pdf -> Example_001.pdf while Example_100.pdf -> Example_100.pdf

The first part renamed files to Example.1.pdf so I could parse them with a single delimiter, but it gave me errors on the second step (cmdlet rename-item at command pipeline position 1 supply values for the following parameters: path)

Get-ChildItem of* | rename-item -newname { $_.Name -replace '_','.' }
Get-ChildItem of* | 
    foreach {
        $nameArray = $_.Split('.')
        $ExampleNumber = $nameArray[1]
        rename-item -path $Path -newname $nameArray[0] $ExampleNumber $nameArray[2]
    }

But if I can get something like this to work then I can play around with $ExampleNumber

Then I tried using regular expressions. Had this worked it would have padded the single digit files and then I could make a second pass for double digit files. But it didn't rename anything.

Get-ChildItem ex* | rename-item -newname { $_ -replace '(.*)(\d{1})\.pdf', 'Example_0$2.pdf'}

Any help is appreciated.

CodePudding user response:

Note the $_ inside the -NewName block is of type FileInfo.

Here's my suggestion:

Get-ChildItem ex* | Rename-Item -NewName {
  [void]($_.Name -match "\d ")
  $_.Name -replace "\d ", (([int]$Matches[0]).ToString("000"))
}

Or alternatively:

Get-ChildItem ex* |
 Rename-Item -NewName {
   $_.Name -replace "\d ", (([int][regex]::match($_.Name, "\d ").value).ToString("000"))}
  • Related