Powershell 复制项目退出代码 1

Powershell Copy-Item Exit code 1

我有一个脚本,其中包含几个我想复制的文件,我或多或少是这样做的。

Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force

等等。

现在,如果有任何文件未被复制,我希望此脚本以 1 退出。

提前致谢

您所要求的与 bash 中的 set -e 选项类似,它会导致脚本在命令发出失败信号时立即退出(条件语句除外)[1].

PowerShell 没有这样的选项[2],但您可以模拟它:

# Set up a trap (handler for when terminating errors occur).
Trap { 
    # Print the error. 
    # IMPORTANT: -ErrorAction Continue must be used, because Write-Error
    #            itself would otherwise cause a terminating error too.
    Write-Error $_ -ErrorAction Continue
    exit 1 
}

# Make non-terminating errors terminating.
$ErrorActionPreference = 'Stop'

# Based on $ErrorActionPreference = 'Stop', any error reported by
# Copy-Item will now cause a terminating error that triggers the Trap
# handler.
Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force

# Failure of an EXTERNAL PROGRAM must be handled EXPLICITLY,
# because `$ErrorActionPreference = 'Stop'` does NOT apply.
foo.exe -bar
if ($LASTEXITCODE -ne 0) { Throw "foo failed." } # Trigger the trap.

# Signal success.
exit 0

:

  • PowerShell-在内部,退出代码用于错误处理;它们通常只在从 PowerShell 调用外部程序时,或者当 PowerShell / PowerShell 脚本需要向外界发出成功与失败信号时(当从另一个 shell 调用时,例如 cmd Windows,或在类 Unix 平台上 bash

  • PowerShell 的自动 $LASTEXITCODE 变量反映了调用 exit <n>.

  • 的最近执行的外部程序/PowerShell 脚本的退出代码
  • 调用外部(console/terminal)程序通过非零退出代码发出失败信号不会触发trap块,因此上面代码片段中的显式 throw 语句。

  • 除非您明确设置退出代码,否则最后执行的任何外部程序的退出代码都会决定脚本的整体退出代码。

[1] 请注意,此选项有其批评者,因为关于何时容忍失败以及何时导致脚本中止的确切规则很难记住 - 请参阅 http://mywiki.wooledge.org/BashFAQ/105

[2] this RFC proposal 中正在讨论可能增加对它的支持。

你可以这样做,它会退出并显示 powershell 命令错误的次数。

$errorcount = $error.count

Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force

exit $error.count - $errorcount