powershell - 在 Windows PowerShell 中有条件地执行进程(例如 Bash 中的 && 和 || 运算符)

标签 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

PowerShell 将要求我执行以下操作,假设我实际上可以在 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 命令提示符)之​​间的区别,我需要适应,但如果有更简洁的方法,我很想知道。

最佳答案

您可以创建一个函数来执行此操作,但我所知道的没有直接的方法来执行此操作。

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 环境。

关于powershell - 在 Windows PowerShell 中有条件地执行进程(例如 Bash 中的 && 和 || 运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1917271/

相关文章:

powershell - 在屏幕和变量中调用表达式输出

python - +\Python 中的运算符

python 3 : Exception or return code when resource limit exceeded?

c# - 当 Main 抛出异常时,Environment.ExitCode 不受尊重。如何返回非零退出代码并抛出异常?

c# - C# 中 EXIT_SUCCESS 和 EXIT_FAILURE 的等价物是什么?

windows - 如何在PowerShell一线式中转义空间

powershell - 使用 PowerShell 连接到 JMX

windows - Powershell存在本地用户ADSI

java - 简单的 Java 正则表达式不起作用

运算符的 C++ 链接 << for std::cout like usage