在Windows PowerShell中有条件地执行过程(例如Bash中的&&和||运算符) [英] Execute process conditionally in Windows PowerShell (e.g. the && and || operators in Bash)
问题描述
我想知道是否有人知道根据前一个程序的退出成功/失败有条件地执行程序的方法.如果在没有测试LASTEXITCODE变量的情况下成功退出了program1,我有什么办法可以在program1之后立即执行program2?我试过-band和-and运算符无济于事,尽管我觉得它们无论如何都不会工作,最好的替代方法是分号和if语句的组合.我的意思是,当涉及到从Linux上的源代码自动构建软件包时,&&操作员不能被打败:
I'm wondering if anybody knows of a way to conditionally execute a program depending on the exit success/failure of the previous program. Is there any way for me to execute a program2 immediately after program1 if program1 exits successfully without testing the LASTEXITCODE variable? I tried the -band and -and operators to no avail, though I had a feeling they wouldn't work anyway, and the best substitute is a combination of a semicolon and an if statement. I mean, when it comes to building a package somewhat automatically from source on Linux, the && operator can't be beaten:
# Configure a package, compile it and install it
./configure && make && sudo make install
PowerShell将要求我执行以下操作,假设我实际上可以在PowerShell中使用相同的构建系统:
PowerShell would require me to do the following, assuming I could actually use the same build system in PowerShell:
# Configure a package, compile it and install it
.\configure ; if ($LASTEXITCODE -eq 0) { make ; if ($LASTEXITCODE -eq 0) { sudo make install } }
当然,我可以使用多行代码,将其保存在文件中并执行脚本,但是这样做的目的是要简洁(保存击键).也许这只是PowerShell和Bash(甚至包括支持&&运算符的内置Windows命令提示符)之间的区别,但是如果有更清洁的方法,我很乐意要知道.
Sure, I could use multiple lines, save it in a file and execute the script, but the idea is for it to be concise (save keystrokes). Perhaps it's just a difference between PowerShell and Bash (and even the built-in Windows command prompt which supports the && operator) I'll need to adjust to, but if there's a cleaner way to do it, I'd love to know.
推荐答案
您可以创建一个函数来执行此操作,但是据我所知没有直接的方法.
You could create a function to do this, but there is not a direct way to do it that I know of.
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-conditionally(@(".\configure","make","sudo make install"))
在没有方便的Powershell环境的情况下,可能会出现一些错误.
There are probably a few errors there this is off the cuff without a powershell environment handy.
这篇关于在Windows PowerShell中有条件地执行过程(例如Bash中的&&和||运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!