From what I know, PowerShell doesn\'t seem to have a built-in expression for the so-called ternary operator.
For example, in the C language, which supports the terna
PowerShell currently doesn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
See: PowerShell Inline If (IIf)
The closest PowerShell construct I've been able to come up with to emulate that is:
@({'condition is false'},{'condition is true'})[$condition]
Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.
Example,
$WinVer = switch ( Test-Path $Env:windir\SysWOW64 ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
Since a ternary operator is usually used when assigning value, it should return a value. This is the way that can work:
$var=@("value if false","value if true")[[byte](condition)]
Stupid, but working. Also this construction can be used to quickly turn an int into another value, just add array elements and specify an expression that returns 0-based non-negative values.
Since I have used this many times already and didn't see it listed here, I'll add my piece :
$var = @{$true="this is true";$false="this is false"}[1 -eq 1]
ugliest of all !
kinda source
As of PowerShell version 7, the ternary operator is built into PowerShell.
1 -gt 2 ? "Yes" : "No"
# Returns "No"
1 -gt 2 ? 'Yes' : $null
# Get a $null response for false-y return value