In powershell, how can I use Rename-Item to output the old and new file names at the same time?
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)"}