Powershell:如何运行外部命令并单行检查其成功? [英] Powershell: How to run an external command and checks its success in a single line?

查看:301
本文介绍了Powershell:如何运行外部命令并单行检查其成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中,我可以这样做:

In bash, I can do this:

if this_command >/dev/null 2>&1; then
  ANSWER="this_command"
elif that_command >/dev/null 2>&1; then
  ANSWER="that_command"
else
  ANSWER="neither command"
fi

但是在Powershell中,我必须这样做:

but in Powershell, I have to do this:

this_command >/dev/null 2>&1
if ($?) {
  ANSWER="this_command"
} else { 
  that_command >/dev/null 2>&1
  if ($?) {
    ANSWER="that_command"
  } else {
    ANSWER="neither command"
  }
}

或与($LASTEXITCODE -eq 0)类似的内容.如何使Powershell看起来像bash?我不是Powershell专家,但是我无法相信它没有提供某种方式来运行命令并在if-elseif-else语句中使用的方式在单个语句中检查其返回代码.对于必须以这种方式进行测试的每个外部命令,此语句将越来越难以阅读.

or something similar with ($LASTEXITCODE -eq 0). How do I make the Powershell look like bash? I'm not a Powershell expert, but I cannot believe that it doesn't not provide some means of running a command and checking its return code in a single statement in a way that could be used in an if-elseif-else statement. This statement would be increasingly difficult to read with every external command that must be tested in this way.

推荐答案

对于PowerShell cmdlet,您可以执行与bash中完全相同的操作.您甚至不需要在每个分支中进行单独的分配.只需输出要分配的内容,然后将整个条件的输出收集到一个变量中即可.

For PowerShell cmdlets you can do the exact same thing you do in bash. You don't even need to do individual assignments in each branch. Just output what you want to assign and collect the output of the entire conditional in a variable.

$ANSWER = if (Do-Something >$null 2>&1) {
    'this_command'
} elseif (Do-Other >$null 2>&1) {
    'that_command'
} else {
    'neither command'
}

对于外部命令,它稍有不同,因为PowerShell将评估命令输出,而不是退出代码/状态(具有空输出).但是您可以在子表达式中运行命令并输出状态以获得所需的结果.

For external commands it's slightly different, because PowerShell would evaluate the command output, not the exit code/status (with empty output evaluating to "false"). But you can run the command in a subexpression and output the status to get the desired result.

$ANSWER = if ($(this_command >$null 2>&1; $?)) {
    'this_command'
} elseif ($(that_command >$null 2>&1; $?)) {
    'that_command'
} else {
    'neither command'
}

请注意,您必须使用一个子表达式($(...)),而不是一个分组表达式((...)),因为您实际上需要连续运行两个命令(运行外部命令,然后输出状态),后者不支持.

Note that you must use a subexpression ($(...)), not a grouping expression ((...)), because you effectively need to run 2 commands in a row (run external command, then output status), which the latter doesn't support.

这篇关于Powershell:如何运行外部命令并单行检查其成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆