Powershell move and rename files

Viewed 2939

I need to swap the names of some files. The files are in the same location so I planned to move them to a staging ground to avoid having two files with the same name. I am attempting to identify the file, based on name parameters, move it to the staging ground and rename it.

I would like to use something similar to the following:

Get-ChildItem ".\" -Recurse | Where-Object { $_.Name -like "*XYZ*"} | Move-Item -Force -Destination "C:\new\" | Rename-Item -NewName { $_.Name -replace 'XYZ','ABC' }

The file moves, but does not rename. Am I not able to pipe the move-item to rename-item?

I would be happy to know if there is a better way to swap the file names of two files without moving, but also would like to know why the above isn't working.

Thanks!

2 Answers

By default Move-Item will not pass the current object along the pipeline.

You can use the -Passthru switch to get that functionality:

Move-Item -Force -Destination "C:\new\" -Passthru

Alternatively, you could cut out Rename-Item by having the Move-item destination be a file:

Get-ChildItem ".\" -Recurse |
    Where-Object { $_.Name -like "*XYZ*"} |
    Move-Item -Force -Destination "C:\new\$($_.Name -replace 'XYZ','ABC')"

Swapping implies two renames which only can take place with one temporary location or a temporary name.

IMO one temporary name is easier.

#Requires -Version 3.0
(Get-ChildItem ".\*XYZ*" -File -Recurse) | ForEach-Object {
    $Swap = $_.Replace("XYZ","ABC")
    If (Test-Path $Swap){
      Rename-Item $Swap -NewName "$Swap.bak"
      $_ | Rename-Item -NewName $Swap
      Rename-Item "$Swap.bak" -NewName $_.FullName
    } else {
      $_ | Rename-Item -NewName $Swap
    }
}
Related