And*_*ndy 31 syntax powershell command-execution
已经有问题解决我的问题(我可以让&&在Powershell中工作吗?),但有一点不同.我需要两个命令的OUTPUT.看,如果我只是运行:
(command1 -arg1 -arg2) -and (command2 -arg1)
Run Code Online (Sandbox Code Playgroud)
我不会看到任何输出,而是stderr消息.正如所料,只需输入:
command1 -arg1 -arg2 -and command2 -arg1
Run Code Online (Sandbox Code Playgroud)
给出语法错误.
Kei*_*ill 28
试试这个:
$(command -arg1 -arg2 | Out-Host;$?) -and $(command2 -arg1 | Out-Host;$?)
Run Code Online (Sandbox Code Playgroud)
这&&是一个子表达式,允许您在包含管道的内部指定多个语句.然后执行命令和管道,$()以便您可以看到它.下一个语句(子表达式的实际输出)应该输出,Out-Host即最后一个命令的成功结果.
这$?适用于本机命令(控制台exe),但对于cmdlet,它留下了一些需要的东西.也就是说,$?只有$?当cmdlet遇到终止错误时才会返回.似乎$false至少需要三种状态(失败,成功和部分成功).因此,如果您使用的是cmdlet,则效果会更好:
$(command -arg1 -arg2 -ev err | Out-Host;!$err) -and
$(command -arg1 -ev err | Out-Host;!$err)
Run Code Online (Sandbox Code Playgroud)
这种打击仍然存在.也许这样的事情会更好:
function ExecuteUntilError([scriptblock[]]$Scriptblock)
{
foreach ($sb in $scriptblock)
{
$prevErr = $error[0]
. $sb
if ($error[0] -ne $prevErr) { break }
}
}
ExecuteUntilError {command -arg1 -arg2},{command2-arg1}
Run Code Online (Sandbox Code Playgroud)
Powershell 7 preview 5 有它们。我不知道为什么在没有通知或解释的情况下将其删除。 https://devblogs.microsoft.com/powershell/powershell-7-preview-5/ 这将根据问题要求给出两个命令的输出。
echo 'hello' && echo 'there'
hello
there
echo 'hello' || echo 'there'
hello
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24312 次 |
| 最近记录: |