如何将 Powershell 命令的输出用作另一个 Powershell 命令的参数?

How can I use the output of a Powershell command as an argument to another Powershell command?

我想折叠这些 Powershell 命令:

$colour = ""
$colour1 = "Red"
$colour2 = "Green"
if ($var -eq 0) {
    # failure
    $colour = $colour1
} Else {
    # success
    $colour = $colour2
}
Write-Host ("Answer = " + $var) -ForegroundColor $colour

成一行,使用上面 if 表达式的输出作为 Write-Host 的输入参数,类似于:

Write-Host ("Answer = " + $var) -ForegroundColor &{if ($var -eq 0) {'Red'} else {'Green'}

我尝试过但失败的事情:

Write-Host ("Answer = " + $var) -ForegroundColor &{if ($var -eq 0) {'Red'} else {'Green'}
Write-Host ("Answer = " + $var) -ForegroundColor `&{if ($var -eq 0) {'Red'} else {'Green'}`
Write-Host ("Answer = " + $var) -ForegroundColor `{if ($var -eq 0) {'Red'} else {'Green'}`
Write-Host ("Answer = " + $var) -ForegroundColor &`{if ($var -eq 0) {'Red'} else {'Green'}`
Write-Host ("Answer = " + $var) -ForegroundColor (&`{if ($var -eq 0) {'Red'} else {'Green'}`)
Write-Host ("Answer = " + $var) -ForegroundColor `{if ($var -eq 0) {return 'Red'} else {return 'Green'}`
Write-Host ("Answer = " + $var) -ForegroundColor `&{if ($var -eq 0) {return 'Red'} else {return 'Green'}`
Write-Host ("Answer = " + $var) -ForegroundColor `&{if ($var -eq 0) {return "Red"} else {return "Green"}`
Write-Host ("Answer = " + $var) -ForegroundColor &{if ($var -eq 0) {return "Red"} else {return "Green"}
Write-Host ("Answer = " + $var) -ForegroundColor &{if ($var -eq 0) {return "Red"} else {return "Green"}}
Write-Host ("Answer = " + $var) -ForegroundColor `&{if ($var -eq 0) {return "Red"} else {return "Green"}}`
Write-Host ("Answer = " + $var) -ForegroundColor &`{if ($var -eq 0) {return "Red"} else {return "Green"}}`
Write-Host ("Answer = " + $var) -ForegroundColor `{if ($var -eq 0) {return "Red"} else {return "Green"}}`
Write-Host ("Answer = " + $var) -ForegroundColor `if ($var -eq 0) {return "Red"} else {return "Green"}`

要将整个 语句(例如 if)的输出作为命令参数传递,请将它们包含在 $(...)subexpression operator 中。

一个简化的例子:

# Note the use of $(...) around the `if` statement.
PS> $var = 0; Write-Host $(if ($var -eq 0) { 'zero' } else { 'nonzero' })
zero

注意如果只需要一个表达式命令的输出,使用(...)grouping operator 就足够了(而且没有副作用)。

例如,if 语句 的 PowerShell (Core) 7+ 替代项是三元 运算符 ,其用途是一个表达式:

# PowerShell (Core) 7+ only.
# Since an expression is used, (...) is sufficient.
PS> $var = 0; Write-Host ($var -eq 0 ? 'zero' : 'nonzero')
zero

对于命令(管道),(...)也足够了。

# Since a command is used, (...) is sufficient.
Write-Output (Get-Item *.txt | Where-Object Length -ge 1kb)

有关 $(...)(...) 的更多信息,请参阅