Null coalescing in powershell

后端 未结 10 1155
遇见更好的自我
遇见更好的自我 2020-11-29 21:57

Is there a null coalescing operator in powershell?

I\'d like to be able to do these c# commands in powershell:

var s = myval ?? \"new value\";
var x         


        
10条回答
  •  广开言路
    2020-11-29 22:37

    This is only half an answer to the first half of the question, so a quarter answer if you will, but there is a much simpler alternative to the null coalescing operator provided the default value you want to use is actually the default value for the type:

    string s = myval ?? "";
    

    Can be written in Powershell as:

    ([string]myval)
    

    Or

    int d = myval ?? 0;
    

    translates to Powershell:

    ([int]myval)
    

    I found the first of these useful when processing an xml element that might not exist and which if it did exist might have unwanted whitespace round it:

    $name = ([string]$row.td[0]).Trim()
    

    The cast to string protects against the element being null and prevents any risk of Trim() failing.

提交回复
热议问题