如何使用 Powershell 命令的输出作为另一个 Powershell 命令的参数?
Posted
技术标签:
【中文标题】如何使用 Powershell 命令的输出作为另一个 Powershell 命令的参数?【英文标题】:How can I use the output of a Powershell command as an argument to another Powershell command? 【发布时间】:2021-09-11 15:18:39 【问题描述】:我想折叠这些 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"`
【问题讨论】:
【参考方案1】:要将整个语句(例如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+ 替代方案 statement 是三元 operator,其用途是 expression :
# 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)
有关$(...)
与(...)
的更多信息,请参阅this answer。
【讨论】:
@skeetastax,那是因为您输入错误-ForegroundColor
(缺少 e
),所以参数 name 未被识别,因此 -ForgroundColor
被视为另一个位置 参数打印。换句话说:你的问题是偶然的,这个答案仍然适用。
@skeetastax :) 很容易犯错误。很高兴听到它奏效了。以上是关于如何使用 Powershell 命令的输出作为另一个 Powershell 命令的参数?的主要内容,如果未能解决你的问题,请参考以下文章
Powershell:如何结合 2 个命令的输出将磁盘字母与磁盘 MediaType 相关联?
我正在使用来自 python 的 powershell 命令获取一些数据,而 Windows 中没有 cmd!如何将此输出分配给字符串变量?