Powershell复制项目退出代码1
我有一个脚本和几个文件,我想复制,我这样做或多或少Powershell复制项目退出代码1,powershell,error-handling,exit-code,copy-item,Powershell,Error Handling,Exit Code,Copy Item,我有一个脚本和几个文件,我想复制,我这样做或多或少 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],但您可以模拟它: #
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调用时,例如在Windows上调用
,或在类Unix平台上调用cmd
)bash
- PowerShell的automatic
变量反映了最近执行的名为$LASTEXITCODE
的外部程序/PowerShell脚本的退出代码exit
- 通过非零退出代码向外部(控制台/终端)程序发出故障信号的调用不会触发
块,因此在上面的代码段中会出现显式trap
语句throw
- 除非显式设置退出代码,否则最后执行的外部程序的退出代码将决定脚本的总体退出代码
[1] 请注意,此选项有其批评者,因为关于何时允许失败以及何时导致脚本中止的确切规则很难记住-请参阅
[2] 正在中讨论可能添加对它的支持。您可以执行类似的操作,它将随着powershell命令错误数的增加而退出
$errorcount=$error.count
复制项目xxx1 yyy1-强制
复制项目xxx2 YYYY2-强制
复制项目xxx3 YYYY3-强制
复制项目xxx4 YYYY4-强制
退出$error.count-$errorcount