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?
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?
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)
}
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 :)
You can do it like this:
gci . | %{ rename-item -Path $_.fullname -NewName ($_.name + 1); Write-Host "Renamed $($_.fullname) to $($_.name + 1)"}
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);
}
}