Powershell: Why does Rename-Item not work as a piped command?

Viewed 588

In this script, everything is working as I expect for the most part. However, the rename operation will only work outside of these piped commands

 Get-ChildItem -Path $folderpath -Filter $folderfile | Move-Item - 
Destination $destination | sleep 5  | Out-File -FilePath $logpath -Append

If I try to do the rename as part of the piped commands, it simply doesn't work. Anywhere outside of that and it will work for a single iteratrion of the filewatcher, and then no more. Why will the rename not work as a piped command?

Get-ChildItem -Path $folderpath -Filter $folderfile | Move-Item -Destination $destination | Rename-Item $destination$folderfile -NewName $newname  | Out-File -FilePath $logpath -Append
1 Answers

Move-Item does not output to the pipeline by default. Use the -PassThru switch:

-PassThru
Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.

That will pipe it directly into Rename-Item and you have to specify -NewName only:

Get-ChildItem -Path $folderpath -Filter $folderfile | 
Move-Item -Destination $destination -PassThru |
Rename-Item -NewName $newname -PassThru |
Out-File -FilePath $logpath -Append

Also, you don't even have to use Rename-Item at all but move it directly to the final target directory + name (assuming $destination is a directory path):

Get-ChildItem -Path $folderpath -Filter $folderfile | 
Move-Item -Destination (Join-Path $destination $newname) -PassThru |
Out-File -FilePath $logpath -Append
Related