You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell Zip归档中子目录指定扩展名文件未被排除的问题

解决PowerShell递归排除指定扩展名文件并压缩的问题

问题原因

Get-ChildItem -Recurse -Exclude 的执行逻辑是先递归获取所有项(包含目录),再对结果整体应用排除规则。但实际过程中,子目录会被先保留,其下的目标扩展名文件会直接纳入结果,导致过滤失效。

修复方案

方案1:通过Where-Object精准过滤文件扩展名

指定只获取文件,再用Where-Object排除目标扩展名,确保所有层级的文件都被过滤:

$files = Get-ChildItem -Recurse -File -Path "$env:USERPROFILE\dir" | Where-Object {
    $_.Extension -notin @('.exe', '.dll', '.dat')
}

Compress-Archive            `
  -Update                   `
  -Path $files              `
  -CompressionLevel Fastest `
  -Destination "$env:USERPROFILE\Desktop\archive.zip"

方案2:结合-File与-Exclude参数

添加-File参数让Get-ChildItem仅返回文件,此时-Exclude会直接对所有层级的文件生效:

$files = Get-ChildItem -Recurse -File -Path "$env:USERPROFILE\dir" -Exclude @('*.exe','*.dll', '*.dat')

Compress-Archive            `
  -Update                   `
  -Path $files              `
  -CompressionLevel Fastest `
  -Destination "$env:USERPROFILE\Desktop\archive.zip"

补充:保留空目录的处理

如果需要保留归档中的空目录,可单独获取目录并合并到文件列表:

$files = Get-ChildItem -Recurse -File -Path "$env:USERPROFILE\dir" -Exclude @('*.exe','*.dll', '*.dat')
$dirs = Get-ChildItem -Recurse -Directory -Path "$env:USERPROFILE\dir"
$allItems = $files + $dirs

Compress-Archive            `
  -Update                   `
  -Path $allItems           `
  -CompressionLevel Fastest `
  -Destination "$env:USERPROFILE\Desktop\archive.zip"

内容的提问来源于stack exchange,提问作者Nickotine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:04:57