Powershell复制项目退出代码1 [英] Powershell Copy-Item Exit code 1
问题描述
我有一个脚本,其中包含多个文件,我想复制,或多或少都这样做。
I have a script with several files I'd like to copy and I do it more or less like so.
Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force
等等。
现在,我希望此脚本以1退出没有复制任何文件。
Now I'd like this script to exit with 1 if any of the files was not copied.
预先感谢
推荐答案
您要的是类似于 bash
中的 set -e
选项,如果命令发出信号,该脚本会立即退出失败(有条件的情况除外) [1] 。
What you're asking for is similar to the set -e
option in bash
, which causes a script to exit instantly in the event that a command signals failure (except in conditionals)[1].
PowerShell没有这样的选项 [2] ,但是您可以模拟它:
PowerShell has no such option[2], but you can emulate it:
# 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上为c $ c>,在类Unix平台上为
bash
)。
PowerShell-internally, exit codes are not used in error handling; they typically only come into play when invoking external programs from PowerShell, or when PowerShell / a PowerShell script needs to signal success vs. failure for the outside world (when called from another shell, such as
cmd
on Windows, orbash
on Unix-like platforms).
PowerShell的自动 $ LASTEXITCODE
变量反映了最近执行的名为 exit< n>
的外部程序/ PowerShell脚本的退出代码。
PowerShell's automatic $LASTEXITCODE
variable reflects the exit code of the most recently executed external program / PowerShell script that called exit <n>
.
对通过非零退出代码发出故障信号的外部(控制台/终端)程序的调用不会触发 trap
块,因此上面的代码段中显式的 throw
语句。
Calls to external (console/terminal) programs that signal failure via a nonzero exit code do not trigger the trap
block, hence the explicit throw
statement in the snippet above.
[1]请注意,此选项有其批评之处,因为围绕失败时的确切规则是可以容忍的,并且当它导致脚本中止时很难记住-请参阅 http://mywiki.wooledge。 org / BashFAQ / 105
[2]可能在此RFC提案。
这篇关于Powershell复制项目退出代码1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!