开发者

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 worki开发者_JAVA百科ng fine. But the renamed files are not being copied over to the backup location. What I am doing wrong here?


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 }


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} 


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"
         }


One liner:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜