Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bulk rename files using PowerShell?

Tags:

powershell

tfs

I'm trying to recursively rename a bunch of TFS folders using tf rename, PowerShell and a regular expression but I'm having some issues with PowerShell as I haven't spent much time with it. This is what I've put together so far to replace a leading 5 with 2.3.2 but it isn't working:

dir | foreach { tf rename $_ { $_.Name -replace '^5', '2.3.2' } }

Actual result:

Unrecognized command option 'encodedCommand'.
Unrecognized command option 'encodedCommand'.
Unrecognized command option 'encodedCommand'.
Unrecognized command option 'encodedCommand'.
...etc.

Update:

I got a little closer by doing the following instead:

dir | foreach { $newname = $_.Name -replace "^5", "2.3.2"; tf rename $_ $newname }

My next goal is to make this recurse subdirectories but this seems a bit more challenging (changing it to dir -recurse makes it quit after the parent folders for some reason).

like image 773
Luke Avatar asked Aug 12 '09 18:08

Luke


1 Answers

I would first filter by 5* so you only process names that start with 5. Also, in this case since tf.exe isn't a PowerShell cmdlet, you don't want to use a scriptblock to determine a new name. Just use a grouping expression like so:

dir -filter 5* | foreach { tf rename $_ ($_.Name -replace '^5', '2.3.2')}

BTW, when you are trying to debug parameter passing to a native EXE like this it is immensely helpful to use the echoargs.exe utilty from the PowerShell Community Extensions. This is what it told me about your original approach:

6# dir -filter 5* | foreach { echoargs rename $_ { $_.Name -replace '^5', '2.3.2' } }
Arg 0 is <rename>
Arg 1 is <5foo.txt>
Arg 2 is <-encodedCommand>
Arg 3 is <IAAkAF8ALgBOAGEAbQBlACAALQByAGUAcABsAGEAYwBlACAAJwBeADUAJwAsACAAJwAyAC4AMwAuADIAJwAgAA==>
Arg 4 is <-inputFormat>
Arg 5 is <xml>
Arg 6 is <-outputFormat>
Arg 7 is <text>
like image 125
Keith Hill Avatar answered Sep 25 '22 22:09

Keith Hill