【问题标题】:Powershell Copy files from multiple subfolders to single folder ignoring duplicates [duplicate]Powershell将文件从多个子文件夹复制到单个文件夹,忽略重复项[重复]
【发布时间】:2015-07-14 00:33:28
【问题描述】:

Total N00b 到 Powershell 并且已经有一个脚本使用 Robocopy 将文件及其目录结构复制到另一个文件夹,然后将它们从子文件夹复制到根文件夹。是的,我尝试过搜索,但找不到任何有用的东西。

这是第二步的Powershell命令:

get-childitem -rec -include *.* | copy-item -destination 'yourpath'

有什么我可以添加到这个的,这样它就不会复制目标目录(即文件夹结构的根目录)中已经存在的文件(根据文件名)?

提前致谢

【问题讨论】:

  • 将您的 copy-item 命令包含在一个 IF 块中,用于测试目标文件是否存在。
  • 谢谢@TonyHinkle 所以我基本上需要它来检查它在子文件夹中找到的每个项目在主文件夹中不存在。试过这个:get-childitem -rec -include *.* | if(!(Test-Path -Path 'C:\Users\Public\Tictocwatches v2.0\Images\Images Matched to Current Data 03-05-2015')) { copy-item -destination 'C:\Users\Public\Tictocwatches v2.0\Images\Images Matched to Current Data 03-05-2015' } 但它说 if 无效或位于错误的位置。 (那里可能还有一大堆其他错误,但那是 powershell 向我抛出的错误。)
  • 谢谢@GrahamGold,正如我所说,我已经搜索过但没有找到任何结果。这似乎做了我想做的事,或者至少为我指明了正确的方向。 :)
  • 再次@GrahamGold 谢谢你似乎已经完成了这项工作。有什么方法可以更显着地将人们重定向到该线程?
  • @GrahamGold - 您可以将文件是否存在的测试移动到 cop-item cmdlet 之前的 Where-Object 条件中,就像我在这篇文章中的回答一样。

标签: file powershell robocopy


【解决方案1】:

一种选择是将 get-childitem 的输出通过管道传输到 Test-Path cmdlet 以检查目标文件是否存在:

get-childitem -rec -include *.* | ? { !(Test-Path "yourpath\$($_.Name)") } | copy-item -destination 'yourpath'

【讨论】:

  • 我破解的方法是get-childitem -rec -include *.* | Foreach-object {If (-Not (Test-path $target$_.)) {copy-item -path $_.fullname -destination $target$_}} 我显然不是@dugas 的Powershell 大师。 :)
  • @dugas 不是大师 :)
  • 几个问题: 1 - 我可以将 get-childitem 限制为 在子文件夹中查找具有特定扩展名的文件吗?如果它只是忽略根文件夹中已经存在的文件,将节省大量处理。 (我猜它会像 ./*/*.jpg 而不是 .,不过我可能错了。) 2 - dugas 我接受它我可以插入我的绝对路径在它说“你的路径”的地方,即使路径中有空格,也可以将所有内容保留在引号内? 3 - @TonyHinkle:不是$target$_。需要在某处设置为变量吗?
  • 要获取子目录,从另一个只返回文件夹的 get-childitem 开始(PSIsContainer 上的过滤器):Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | get-childitem -rec -include *.* | ? { !(Test-Path "yourpath\$($_.Name)") } | copy-item -destination 'yourpath'
  • 是的,$target 将是一个我使用的变量,而不是将路径名作为字符串放在那里。也可以写成'd:\mypath'$_
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2022-08-04
  • 2015-05-23
相关资源
最近更新 更多