9

I'd like to select a list of files using Get-ChildItem piped to Rename-Item and have the output display text with each line showing something like "Renamed oldfilename to newfilename".

How can I do this?

Anthony Neace
  • 25,013
  • 7
  • 114
  • 129
James World
  • 29,019
  • 9
  • 86
  • 120
  • 1
    I'm a bit of a powershell ignoramus, so I'm floundering a little. I've played with Tee-Object and -outvariable and -passthru but to be honest I don't really know what I'm doing and this feels like it should be an easy thing to do. – James World Sep 06 '12 at 09:47

4 Answers4

11
Get-Childitem C:\Temp |
    Foreach-object {
        $OldName = $_.name; 
        $NewName = $_.name -replace 'temp','test'; 
        Rename-Item -Newname $NewName; 
        Write-Output $("Renamed {0} to {1}" -f $OldName,$NewName)
        }
khr055
  • 28,690
  • 16
  • 36
  • 48
JJ Willemen
  • 126
  • 2
9

One simple solution is to run rename-item with -WhatIf. This will display something like

PS H:\test> gci | rename-item -newname { $_.name -replace 'temp','test' } -WhatIf
What if: Performing operation "Rename File" on Target "Item: H:\test\temp1 Destination: H:\test\test1".

Good enough, or do you need it to do it while also doing the operation?

EDIT: An even simpler solution, use -Verbose. Does the same as the -WhatIf, but also performing the operation :)

carlpett
  • 12,203
  • 5
  • 48
  • 82
  • Thanks for this - I'd like to get nice formatting on the output if possible. Verbose and what-if work but the output is not very readable. I will up-vote this one though. – James World Sep 06 '12 at 10:06
4

You can do it like this:

gci . | %{ rename-item -Path $_.fullname -NewName ($_.name + 1); Write-Host "Renamed $($_.fullname) to $($_.name + 1)"}
manojlds
  • 290,304
  • 63
  • 469
  • 417
0

I know this is a bit old but I do have a problem with all of them. This will loop thru all the files and rename them even if the name doesn't change! That's unneeded over-head.

I've add a few more options.

    Get-ChildItem -Filter *.txt -Recurse -Path "C:\temp" | 
    Foreach-object {
        
        $OldName = $_.name; 
        $NewName = $_.name -replace 'temp','test'; 
        
        If ( $OldName -ne $NewName ){
            Rename-Item -Path $_.PSPath -Newname $NewName; 
            Write-Output $("Renamed {0} to {1}" -f $OldName,$NewName);
            }
        }
Dharman
  • 30,962
  • 25
  • 85
  • 135
SQLEagle
  • 19
  • 4