PowerShell 中的条件执行(&& 和 ||) [英] conditional execution (&& and ||) in powershell

查看:66
本文介绍了PowerShell 中的条件执行(&& 和 ||)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有问题解决了我的问题(我可以得到 &&在 Powershell 中工作?),但有一个区别.我需要来自两个命令的 OUTPUT.看,如果我只是运行:

There's already question addressing my issue (Can I get && to work in Powershell?), but with one difference. I need an OUTPUT from both commands. See, if I just run:

(command1 -arg1 -arg2) -and (command2 -arg1)

我不会看到任何输出,但会看到 stderr 消息.而且,正如预期的那样,只需输入:

I won't see any output, but stderr messages. And, as expected, just typing:

command1 -arg1 -arg2 -and command2 -arg1 

给出语法错误.

推荐答案

2019:Powershell 团队是 考虑向 Powershell 添加对 && 的支持 - 在此 GitHub PR 中权衡

2019: the Powershell team are considering adding support for && to Powershell - weigh in at this GitHub PR

试试这个:

$(command -arg1 -arg2 | Out-Host;$?) -and $(command2 -arg1 | Out-Host;$?)

$() 是一个子表达式,允许您在包含管道中指定多个语句.然后执行命令和管道到 Out-Host 以便您可以看到它.下一个语句(子表达式的实际输出)应该输出 $? 即最后一个命令的成功结果.

The $() is a subexpression allowing you to specify multiple statements within including a pipeline. Then execute the command and pipe to Out-Host so you can see it. The next statement (the actual output of the subexpression) should output $? i.e. the last command's success result.

$? 适用于本机命令(控制台 exe 的),但对于 cmdlet,它留下了一些不足之处.也就是说,$? 似乎只在 cmdlet 遇到终止错误时返回 $false.看起来 $? 至少需要三个状态(失败、成功和部分成功).因此,如果您使用的是 cmdlet,则效果会更好:

The $? works fine for native commands (console exe's) but for cmdlets it leaves something to be desired. That is, $? only seems to return $false when a cmdlet encounters a terminating error. Seems like $? needs at least three states (failed, succeeded and partially succeeded). So if you're using cmdlets, this works better:

$(command -arg1 -arg2 -ev err | Out-Host;!$err) -and 
$(command -arg1 -ev err | Out-Host;!$err)

这种打击还在.也许这样的事情会更好:

This kind of blows still. Perhaps something like this would be better:

function ExecuteUntilError([scriptblock[]]$Scriptblock)
{
    foreach ($sb in $scriptblock)
    {
        $prevErr = $error[0]
        . $sb
        if ($error[0] -ne $prevErr) { break }
    }
}

ExecuteUntilError {command -arg1 -arg2},{command2-arg1}

这篇关于PowerShell 中的条件执行(&& 和 ||)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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