Based on this answer I tried to create another operator (alias) that reuses that ternary one, and I get error when executing the command:
The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name , a script block, or a CommandInfo object.
The error is raised on the line when a value from ternary operator is being returned. I'm pretty much stuck with it and I don't understand why this happens.
The code:
Function Invoke-Ternary {
[CmdletBinding()]
Param(
[scriptblock]$Condition,
[scriptblock]$TrueBlock,
[scriptblock]$FalseBlock
)
Process {
if (&$Condition) {
return &$TrueBlock
}
return &$FalseBlock
}
}
Function Get-ValueOrDefault {
[CmdletBinding()]
Param(
[scriptblock]$Value,
[scriptblock]$DefaultValue
)
Process {
Invoke-Ternary $Value $Value $DefaultValue
}
}
Set-Alias ?: Invoke-Ternary -Description "PS ternary operator workaround"
Set-Alias ?? Invoke-Ternary -Description "PS default value operator workaround"
Usage:
This works fine:
?: { $non_existing_variable } { $non_existing_variable } {'default'}
This throws the error mentioned above:
?? { $non_existing_variable } { 'default' }