C# and other languages have null-conditionals usually ?.
A?.B?.Do($C);
Will not error out when A or B are null. How do I achieve something similar in powershell, what's a nicer way to do:
if ($A) {
if ($B) {
$A.B.Do($C);
}
}
$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.
$null is one of the automatic variables in PowerShell, which represents NULL. You can use the -eq parameter to check if a string variable equals $null . It returns True if the variable is equal to $null and False if the variable is not equal to $null .
Using IsNullOrEmpty() Static Method PowerShell comes up with a built-in static method named IsNullOrEmpty() which could verify the null or empty check. The above code returns true which mean the string is empty.
Just replace your Write-Host $Bar with $Bar -eq $null and it will return False . Interestingly, if you just do ([string] [NullString]::Value) -eq $null , it returns True , so the coercion is happening as a result of the function.
Powershell 7 Preview 5 has operators that deal with nulls. https://devblogs.microsoft.com/powershell/powershell-7-preview-5/
$a = $null
$a ?? 'is null' # return $a or string if null
is null
$a ??= 'no longer null' # assign if null
$a ?? 'is null'
no longer null
EDIT: Powershell 7 Preview 6 piles on more new operators: https://devblogs.microsoft.com/powershell/powershell-7-preview-6/. Since variable names can have a '?' in the name, you have to surround the variable name with curly braces:
${A}?.${B}?.Do($C)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With