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

如何判断PowerShell中Compress-Archive压缩命令是否执行成功

PowerShell判断Compress-Archive执行结果的方法

Compress-Archive默认返回Void类型,不会直接输出布尔值标识执行状态,可以通过以下两种PowerShell内置机制判断执行结果:

方案1:使用$?自动变量(最简实现)

PowerShell内置的$?变量会自动存储上一条命令的执行状态:上一条命令执行成功返回$true,执行失败返回$false。你代码中的对应逻辑可以直接修改为:

$_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip"
if ($?) {
  echo "$name is zipped"
  $_ | Remove-Item
}

方案2:使用try-catch块捕获错误(更稳妥)

如果需要避免非终止错误导致判断结果不准确,可以给Compress-Archive添加-ErrorAction Stop参数,将所有执行错误转为终止错误,再通过try-catch块捕获处理,示例如下:

try {
  $_ | Compress-Archive -DestinationPath "D:\Myoutput\Archive\$name.zip" -ErrorAction Stop
  echo "$name is zipped"
  $_ | Remove-Item
}
catch {
  Write-Warning "压缩文件$name失败,错误信息:$_"
}

额外注意

执行前请确保目标归档目录D:\Myoutput\Archive存在,否则会触发压缩错误,可以在脚本开头添加以下代码自动创建目录:

if (-not (Test-Path 'D:\Myoutput\Archive')) {
  New-Item -ItemType Directory -Path 'D:\Myoutput\Archive' | Out-Null
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:30:01