How to use the Copy-Item cmdlet correctly to copy piped files

人盡茶涼 提交于 2019-12-08 14:58:09

问题


I am building a small script which should copy all .zip files to a special folder called F:\tempzip.

I tried it with Copy-Item cmdlet, but I didn't manage to do it. The script should copy all files from this folder (recursively) which are ".zip".

This is the part of the script I am talking about:

get-childitem F:\Work\xxx\xxx\xxx -recurse `
   | where {$_.extension -eq ".zip"}       `
   | copy-item F:\tempzip

What do I have to add?


回答1:


When piping items to copy-item you need to tell it that "F:\tempzip" is the destination path.

| Copy-Item -Destination F:\tempzip

You can also cutout piping to the where operator by using Get-ChildItem's parameter -filter.

Get-Childitem "C:\imscript" -recurse -filter "*.zip" | Copy-Item -Destination "F:\tempzip"

Edit: Removal of unnecessary foreach loop and updated explanation.




回答2:


It's a lot simpler than that. Copy-Item has its own -Recurse switch. All you have to do is:

Copy-Item F:\Work\xxx\xxx\xxx\*.zip F:\tempzip -Recurse



回答3:


For whatever reason, the Copy-Item recursion didn't accomplish what I wanted, as mentioned here, and how it is documented to work. If you have a bunch of *.zip or *.jpg files in arbitrarily deep subfolder hierarchies, and you want to copy them to a single place (one flat folder, elsewhere), I had better luck with a piped command involving Get-ChildItem. Say you are currently in the folder containing the root of your search:

Get-ChildItem -Recurse -Include *.zip | Copy-Item -Destination C:\Someplace\Else

That command will copy all the files and not duplicate the folder hierarchies.



来源:https://stackoverflow.com/questions/17972783/how-to-use-the-copy-item-cmdlet-correctly-to-copy-piped-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!