Animesh D
Animesh D

Reputation: 5002

Rename and then copy is not working

I am trying to rename certain files and then copy them to a backup location as below:

gci $src `
    | ?{!$_.psiscontainer -and $_.extension.length -eq 0 -and $_ -match "tmp_\d{1}$"} `
    | %{ ren -path $_.fullname -new ($_.name + ".ext") } `
    | %{ cpi -path $_.fullname -dest $bkup -force} 

The renaming part is working fine. But the renamed files are not being copied over to the backup location. What I am doing wrong here?

Upvotes: 2

Views: 260

Answers (4)

Shay Levy
Shay Levy

Reputation: 126762

One liner:

gci $src | ?{!$_.psiscontainer -and !$_.extension -and $_ -match 'tmp_\d$'} | move-item -dest {"$bkup\$($_.Name + '.ext')"}

Upvotes: 1

zdan
zdan

Reputation: 29450

By default renamed items will not be pushed back onto the pipeline, use the -PassThru switch to pass them on:

gci $src `
    | ?{!$_.psiscontainer -and $_.extension.length -eq 0 -and $_ -match "tmp_\d{1}$"} `
    | %{ ren -path $_.fullname -new ($_.name + ".ext") -PassThru } `
    | %{ cpi -path $_.fullname -dest $bkup -force} 

Upvotes: 2

mjolinor
mjolinor

Reputation: 68273

You accomplish both in one operation with move-item.

gci $src 
    | ?{!$_.psiscontainer -and $_.extension.length -eq 0 -and $_ -match "tmp_\d{1}$"} 
    | %{
         $newname = $_.Name + ".ext"
         move-item -path $_.FullName -dest "$bkup\$newname"
         }

Upvotes: 2

Corey Ross
Corey Ross

Reputation: 2015

Rename-Item doesn't return anything so there is nothing to pipe to Copy-Item. You could just put both commands in the for each block together:

gci $src `
    | ?{!$_.psiscontainer -and $_.extension.length -eq 0 -and $_ -match "tmp_\d{1}$"} `
    | %{ $renamedPath = $_.FullName + ".ext"; `
         ren -path $_.FullName -new $renamedPath; `
         cpi -path $renamedPath -dest $bkup -force }

Upvotes: 4

Related Questions