Question

I'd like to write a short powershell script for renaming files like:

abc(1), abc(2), .., abc(10), ..,  abc(123), .. 

to

abc(001), abc(002), .., abc(010), .., abc(123), ..

Any idea? :)

Was it helpful?

Solution

Try this:

Get-ChildItem abc* | Where {$_ -match 'abc\((\d+)\)'} | 
 Foreach {$num = [int]$matches[1]; Rename-Item $_ ("abc({0:000})" -f $num) -wh }

The Where stage of the pipeline is doing to two things. First, only filenames that match the specified pattern are passed along. Second, it uses a capture group to grab the numeric part of the name which is sitting in $matches[1].

The Foreach stage applies script to each item, represented by $_, passed into it. The first thing it does is to get the "numeric" part of the old filename. Then it uses Rename-Item (PowerShell's rename command) to rename from the old name represented by $_ to the new name that is computed using a formatting string "abc({0:000})" -f $num. In this case, the formatting directive goes in {} where 0 represents the position of the value specified after -f. The :000 is a formatting directive displays number with up to three leading zeros. Finally the -wh is short for -WhatIf which directs potentially destructive operations like Rename-Item to show what it would do without actually doing anything. Once you are satisfied the command is working correctly, remove the -wh and run it again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top