/d-6ren">
gpt4 book ai didi

Powershell:如何运行外部命令并在一行中检查其是否成功?

转载 作者:行者123 更新时间:2023-12-02 23:07:27 26 4
gpt4 key购买 nike

在 bash 中,我可以这样做:

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 中,我必须这样做:

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 语句的方式检查其返回代码。对于必须以这种方式测试的每个外部命令,此语句将越来越难以阅读。

最佳答案

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

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

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

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

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

关于Powershell:如何运行外部命令并在一行中检查其是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com