Ternary operator in PowerShell

后端 未结 13 2084
忘掉有多难
忘掉有多难 2020-11-28 03:56

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

13条回答
  •  隐瞒了意图╮
    2020-11-28 04:27

    I too, looked for a better answer, and while the solution in Edward's post is "ok", I came up with a far more natural solution in this blog post

    Short and sweet:

    # ---------------------------------------------------------------------------
    # Name:   Invoke-Assignment
    # Alias:  =
    # Author: Garrett Serack (@FearTheCowboy)
    # Desc:   Enables expressions like the C# operators: 
    #         Ternary: 
    #              ?  :  
    #             e.g. 
    #                status = (age > 50) ? "old" : "young";
    #         Null-Coalescing 
    #              ?? 
    #             e.g.
    #                name = GetName() ?? "No Name";
    #             
    # Ternary Usage:  
    #         $status == ($age > 50) ? "old" : "young"
    #
    # Null Coalescing Usage:
    #         $name = (get-name) ? "No Name" 
    # ---------------------------------------------------------------------------
    
    # returns the evaluated value of the parameter passed in, 
    # executing it, if it is a scriptblock   
    function eval($item) {
        if( $item -ne $null ) {
            if( $item -is "ScriptBlock" ) {
                return & $item
            }
            return $item
        }
        return $null
    }
    
    # an extended assignment function; implements logic for Ternarys and Null-Coalescing expressions
    function Invoke-Assignment {
        if( $args ) {
            # ternary
            if ($p = [array]::IndexOf($args,'?' )+1) {
                if (eval($args[0])) {
                    return eval($args[$p])
                } 
                return eval($args[([array]::IndexOf($args,':',$p))+1]) 
            }
    
            # null-coalescing
            if ($p = ([array]::IndexOf($args,'??',$p)+1)) {
                if ($result = eval($args[0])) {
                    return $result
                } 
                return eval($args[$p])
            } 
    
            # neither ternary or null-coalescing, just a value  
            return eval($args[0])
        }
        return $null
    }
    
    # alias the function to the equals sign (which doesn't impede the normal use of = )
    set-alias = Invoke-Assignment -Option AllScope -Description "FearTheCowboy's Invoke-Assignment."
    

    Which makes it easy to do stuff like (more examples in blog post):

    $message == ($age > 50) ? "Old Man" :"Young Dude" 
    

提交回复
热议问题