Dus*_*tin 7 powershell operators exit-code
我想知道是否有人知道有条件地执行程序的方法取决于前一个程序的退出成功/失败.如果program1在没有测试LASTEXITCODE变量的情况下成功退出,有没有办法在program1之后立即执行program2?我尝试使用-band和-and运算符无济于事,尽管我觉得它们无论如何都不会工作,最好的替代品是分号和if语句的组合.我的意思是,当在Linux上从源代码自动构建一个包时,&&运算符不能被打败:
# Configure a package, compile it and install it
./configure && make && sudo make install
Run Code Online (Sandbox Code Playgroud)
假设我实际上可以在PowerShell中使用相同的构建系统,PowerShell将要求我执行以下操作:
# Configure a package, compile it and install it
.\configure ; if ($LASTEXITCODE -eq 0) { make ; if ($LASTEXITCODE -eq 0) { sudo make install } }
Run Code Online (Sandbox Code Playgroud)
当然,我可以使用多行,将其保存在文件中并执行脚本,但其目的是简洁(保存击键).也许它只是PowerShell和Bash之间的区别(甚至是支持&&运算符的内置Windows命令提示符)我需要调整,但如果有更清洁的方法,我很想知道.
您可以创建一个函数来执行此操作,但据我所知,没有直接的方法可以执行此操作。
function run-conditionally($commands) {
$ranAll = $false
foreach($command in $commands) {
invoke-command $command
if ($LASTEXITCODE -ne 0) {
$ranAll = $false
break;
}
$ranAll = $true
}
Write-Host "Finished: $ranAll"
return $ranAll
}
Run Code Online (Sandbox Code Playgroud)
然后将其称为类似于
run-conditionally(@(".\configure","make","sudo make install"))
Run Code Online (Sandbox Code Playgroud)
可能存在一些错误,这是即兴的,没有方便的 powershell 环境。
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |