我希望我的PowerShell脚本在我运行的任何命令失败时停止(如bash中的set -e)。我正在使用Powershell命令(New-Object System.Net.WebClient)和程序(.\setup.exe)。
当前回答
对于2021年来到这里的人,这是我的解决方案,涵盖了cmdlet和程序
function CheckLastExitCode {
param ([int[]]$SuccessCodes = @(0))
if (!$?) {
Write-Host "Last CMD failed" -ForegroundColor Red
#GoToWrapperDirectory in my code I go back to the original directory that launched the script
exit
}
if ($SuccessCodes -notcontains $LastExitCode) {
Write-Host "EXE RETURNED EXIT CODE $LastExitCode" -ForegroundColor Red
#GoToWrapperDirectory in my code I go back to the original directory that launched the script
exit
}
}
你可以这样用
cd NonExistingpath
CheckLastExitCode
其他回答
据我所知,Powershell对它调用的子程序返回的非零退出码没有任何自动处理。
到目前为止,我所知道的模仿bash -e行为的唯一解决方案是在每次调用外部命令后添加这个检查:
if(!$?) { Exit $LASTEXITCODE }
对于2021年来到这里的人,这是我的解决方案,涵盖了cmdlet和程序
function CheckLastExitCode {
param ([int[]]$SuccessCodes = @(0))
if (!$?) {
Write-Host "Last CMD failed" -ForegroundColor Red
#GoToWrapperDirectory in my code I go back to the original directory that launched the script
exit
}
if ($SuccessCodes -notcontains $LastExitCode) {
Write-Host "EXE RETURNED EXIT CODE $LastExitCode" -ForegroundColor Red
#GoToWrapperDirectory in my code I go back to the original directory that launched the script
exit
}
}
你可以这样用
cd NonExistingpath
CheckLastExitCode
我来这里也是为了寻找同样的东西。$ErrorActionPreference="Stop"立即杀死我的shell时,我宁愿看到错误消息(暂停)之前,它终止。回到我的批处理敏感性:
IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF
我发现这对我的特定ps1脚本几乎是一样的:
Import-PSSession $Session
If ($? -ne "True") {Pause; Exit}
对@alastairtree的回答做了一点修改:
function Invoke-Call {
param (
[scriptblock]$ScriptBlock,
[string]$ErrorAction = $ErrorActionPreference
)
& @ScriptBlock
if (($lastexitcode -ne 0) -and $ErrorAction -eq "Stop") {
exit $lastexitcode
}
}
Invoke-Call -ScriptBlock { dotnet build . } -ErrorAction Stop
这里的关键区别是:
它使用动词-名词(模仿Invoke-Command) 暗示它在幕后使用调用操作符 模仿内置cmdlet中的-ErrorAction行为 使用相同的退出代码退出,而不是使用新消息抛出异常
我刚接触powershell,但这似乎是最有效的:
doSomething -arg myArg
if (-not $?) {throw "Failed to doSomething"}
推荐文章
- 我如何找到哪个程序正在使用端口80在Windows?
- 在Windows中有像GREP这样的模式匹配实用程序吗?
- 如何在Windows命令提示符下运行.sh ?
- 如何在PowerShell中获得本地主机名?
- 如何从命令行在windows中找到mysql数据目录
- 在没有事件源注册的情况下写入Windows应用程序事件日志
- PowerShell:如何将数组对象转换为PowerShell中的字符串?
- 无法在Windows上从/usr/local/ssl/openssl.cnf加载配置信息
- 从PowerShell ISE中的另一个PS1脚本调用PowerShell脚本PS1
- GIT克隆在windows中跨本地文件系统回购
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 是否有一种方法可以通过双击.ps1文件来使PowerShell脚本工作?
- 为什么这个Windows批处理文件只执行第一行,而在命令shell中执行所有三行?
- 环境变量存储在Windows注册表的哪里?