在Powershell中删除文件时如何指定要排除的多种文件类型

How to specify multiple file types to exclude when deleting files in Powershell

我正在使用以下脚本从安装目录复制文件,然后删除除 XML 文件之外的所有文件。我还想排除 .log.txt 文件被删除。我该如何格式化才能实现这一目标?

如果可以仅下载 XML/LOG/TXT 个文件(包括文件夹结构)而无需返回并删除多余的内容,则加分。

Copy-Item -Path $cis_wild -Destination $target_cis -Container -Recurse
Get-ChildItem -Path $target_cis -Recurse -File | Where {($_.Extension -ne ".xml")} | Remove-Item

使用 -Exclude 参数,它允许您指定 数组 排除通配符模式 - 但请参阅下面的注意事项:

Get-ChildItem -Exclude *.xml, *.txt, *.log -Path $target_cis -Recurse -File | 
  Remove-Item -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf


Post-filtering解决方案,建立在你自己的尝试上:

虽然从 PowerShell 7.2.2 开始,使用给定的 cmdlet 参数直接解决问题通常更可取 - 无论是为了简洁还是性能 - 但有充分的理由单独执行过滤 ,在 Get-ChildItem 后应用它已返回其(未过滤的)结果(这是您尝试的结果):

  • 虽然 -Include / -ExcludeGet-ChildItem -Recurse 一起按预期工作,但它们并非没有它,记住这个事实并不容易 - 请参阅底部。

  • -Include / -ExcludeGet-ChildItem -Recurse 组合 出乎意料地慢 - 甚至比 post-filtering 解决办法:见GitHub issue #8662

Get-ChildItem -Path $target_cis -Recurse -File | 
  Where-Object { $_.Extension -notin '.xml', '.txt', '.log' } |
    Remove-Item -WhatIf

也就是说,从您尝试 ($_.Extension -ne ".xml") 中的 -ne 运算符切换到
-notin 运算符允许放置一个 array RHS 上的字符串以测试 LHS 字符串:

$_.Extension -notin '.xml', '.txt', '.log' returns $true 如果 RHS 数组中不存在 $_.Extension 的值(对每个元素使用隐式 -eq 测试)。


注意事项 从 PowerShell 7.2.2 开始:

  • 完全是因为你的命令用-RecurseGet-ChildItem that -Exclude and -Include work as one would expect; without -Recurse, these parameters exhibit counter-intuitive behavior - see .

    递归遍历
  • 使用 Copy-Item,即使 -Recurse 也不会使 -Include 工作,尽管 -Exclude 大部分情况下会按预期工作:

    • 也就是说,虽然您 应该 能够将 -Include 与多个通配符模式一起使用,以便直接与 Copy-Item -Recurse 中的包含匹配为了限制开始复制的内容,它不起作用。

    • -Include 被错误地应用于 直接目标目录 并且 应用于它:

      • 如果 none 的指定模式匹配 它的 名称,不会复制任何内容
      • 如果任何指定的模式确实匹配其名称,整个目录子树被复制而不过滤.
    • -Exclude,相比之下,mostly 按预期工作:它在目录子树层次结构的每个级别应用排除模式。

      • 如果任何排除模式恰好与直接目标目录的名称相匹配,不会复制任何内容
    • 有关详细讨论,请参阅 ,包括有关如何解释 -Destination 参数的问题。