据我所知,PowerShell似乎没有用于所谓三元运算符的内置表达式。
例如,在支持三元操作符的C语言中,我可以这样写:
<condition> ? <condition-is-true> : <condition-is-false>;
如果PowerShell中没有这样的功能,那么要达到同样的效果(即易于阅读和维护),最好的方法是什么?
据我所知,PowerShell似乎没有用于所谓三元运算符的内置表达式。
例如,在支持三元操作符的C语言中,我可以这样写:
<condition> ? <condition-is-true> : <condition-is-false>;
如果PowerShell中没有这样的功能,那么要达到同样的效果(即易于阅读和维护),最好的方法是什么?
当前回答
尝试powershell的switch语句作为替代,特别是对于变量赋值-多行,但可读。
的例子,
$WinVer = switch ( Test-Path -Path "$Env:windir\SysWOW64" ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
其他回答
$result = If ($condition) {"true"} Else {"false"}
为了在表达式中或作为表达式使用,而不仅仅是赋值,将它包装在$()中,这样:
write-host $(If ($condition) {"true"} Else {"false"})
尝试powershell的switch语句作为替代,特别是对于变量赋值-多行,但可读。
的例子,
$WinVer = switch ( Test-Path -Path "$Env:windir\SysWOW64" ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
Powershell 7有这个功能。
PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes
因为我已经用过很多次了,没有看到它列在这里,我将添加我的部分:
$var = @{$true="this is true";$false="this is false"}[1 -eq 1]
最丑的!
有点源
PowerShell中的三元运算符是在PowerShell version7.0中引入的。
[Condition] ? (output if True) : (output if False)
例01
$a = 5; $b = 6
($a -gt $b) ? "True" : "False"
输出
False
例子02
($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")
输出
5 is less than 6
更多的信息 https://www.tutorialspoint.com/how-ternary-operator-in-powershell-works