Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell move and rename files

Tags:

powershell

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!

like image 887
Garrett Avatar asked Sep 12 '25 00:09

Garrett


1 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')"
like image 158
G42 Avatar answered Sep 13 '25 14:09

G42