Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Conditional in Powershell?

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);
  }
}
like image 890
RaGe Avatar asked Oct 25 '19 14:10

RaGe


People also ask

How do you use null in PowerShell?

$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.

How do you check if a value is null in PowerShell?

$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 .

Is null or empty in PowerShell?

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.

How do I pass a null parameter in PowerShell?

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.


1 Answers

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)
like image 65
js2010 Avatar answered Nov 09 '22 22:11

js2010