powershell - Powershell-复制已知子文件夹中的所有项目,并排除其他所有内容

标签 powershell

我正在尝试复制嵌套在目录内的一些PDF。
这是结构。大约有100个类似于以下结构的目录
顶级文件夹

  • ParentFolder1
  • 子文件夹1
  • 子文件夹2

  • ParentFolder2
  • 子文件夹1
  • 子文件夹2


  • 我想做的是从每个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/

    相关文章:

    powershell - 当我犯错时,如何退出 powershell 中的 >> 提示?

    arrays - 在 PSCustomObject 数组中查询具有最大值的行

    Powershell 输出到 csv 文件

    powershell - 如何使用 powershell 重命名 blob 文件

    arrays - 将Powershell中的对象重定向到其他功能

    powershell - get-aduser -ldapfilter 与 -OR

    powershell - 为 nuget 创建自定义 powershell 脚本,将自定义目标添加到 csproj BeforeBuild 步骤

    powershell - 绕过 Powershell 运行 zsh 命令

    powershell - 从 powershell v3.0 管理网络场

    powershell - 在 PowerShell 中获取方法的参数