-1

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' }
andiDo
  • 309
  • 4
  • 11
SOReader
  • 5,697
  • 5
  • 31
  • 53
  • 1
    `Set-Alias ?? Invoke-Ternary` -> `Set-Alias ?? Get-ValueOrDefault` – Ansgar Wiechers Jan 25 '18 at 11:40
  • @AnsgarWiechers OMG, I can't believe I missed that. I feel so stupid right now :( I'm going to leave the question though, maybe it's gonna' be of any use for somebody else and as a painful reminder for me. I've been on it for couple of hours :) – SOReader Jan 25 '18 at 11:59

1 Answers1

1

I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.


My github topic branch: UtilityModule_Invoke-Operators

Functions:

Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe

Aliases

Set-Alias :?:   Pscx\Invoke-Ternary                     -Description "PSCX alias"
Set-Alias ?:    Pscx\Invoke-TernaryAsPipe               -Description "PSCX alias"
Set-Alias :??   Pscx\Invoke-NullCoalescing              -Description "PSCX alias"
Set-Alias ??    Pscx\Invoke-NullCoalescingAsPipe        -Description "PSCX alias"

Usage

<condition_expression> |?: <true_expression> <false_expression>

<variable_expression> |?? <alternate_expression>

As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}

If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.

andiDo
  • 309
  • 4
  • 11