我有一个脚本,其中包含要复制的几个文件,我或多或少都这样做。
Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force
等等。
现在,如果没有复制任何文件,我希望此脚本以1退出。
提前致谢
最佳答案
您要的内容类似于set -e
中的bash
选项,该选项会导致脚本在命令发出失败信号时立即退出脚本(条件语句除外)[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
注意:
cmd
或类似Unix上的bash
平台)。 $LASTEXITCODE
变量反射(reflect)了最近执行的名为exit <n>
的外部程序/PowerShell脚本的退出代码。 trap
块,因此上面代码段中的显式throw
语句。 [1]请注意,此选项有其批评之处,因为难以容忍何时发生故障以及何时导致脚本中止的确切规则-请参阅http://mywiki.wooledge.org/BashFAQ/105
[2] this RFC proposal中正在讨论可能增加对它的支持。
关于powershell - Powershell复制项目退出代码1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248823/