我正在尝试复制嵌套在目录内的一些PDF。
这是结构。大约有100个类似于以下结构的目录
顶级文件夹
我想做的是从每个
Subfolder1
中的ParentFolder
复制所有内容。在每个ParentFolder
中,Subfolder1都具有相同的名称。我可以使用此命令获取所有文件
Get-ChildItem -Path 'C:\Temp\Powershell' -Recurse -Include *.pdf
但是当我告诉它使用此命令复制文件时Get-ChildItem -Path 'C:\Temp\Powershell' -Recurse -Include *.pdf
ForEach-Object {Copy-Item $_.FullName -Destination 'C:\Temp\Destination'}
它给我这个错误Copy-Item : Cannot bind argument to parameter 'Path' because it is null.
At line:2 char:27
+ ForEach-Object {Copy-Item $_.FullName -Destination 'C:\Temp\Destinati ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CopyItemCommand
我感觉自己已经接近了,但是我想排除所有未命名为Subfolder1
的目录,然后递归复制所有Subfolder1
内容。我尝试在-Include
语句中添加文件夹名称,但未成功。编辑
在Tomalak的帮助下,我能够找出问题并对其进行过滤,以便仅通过每个
Subfolder1
查看ParentFolder
。Get-ChildItem -Path 'C:\Temp\Powershell' -Recurse -Include *.pdf
| Where-Object {$_.PSParentPath -like "*Subfolder1*"}
| ForEach-Object {Copy-Item $_.FullName -Destination 'C:\Temp\Destination'}
最佳答案
Copy-Item
从管道中获取输入,您根本不需要使用ForEach-Object
。
Get-ChildItem -Path 'C:\Temp\Powershell' -Recurse -Include *.pdf | Copy-Item -Destination 'C:\Temp\Destination'
但是,如果需要,您仍然需要将其附加到管道(请注意|
):Get-ChildItem -Path 'C:\Temp\Powershell' -Recurse -Include *.pdf | ForEach-Object {
Copy-Item $_.FullName -Destination 'C:\Temp\Destination'
}
您的代码在额外的一行上完全没有与先前的cmdlet的连接。
关于powershell - Powershell-复制已知子文件夹中的所有项目,并排除其他所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63198927/