Empty parameter is not null

Given this basic function:

Function TestFunction { Param ( [int]$Par1, [string]$Par2, [string]$Par3 ) If ($Par1 -ne $Null) { Write-Output "Par1 = $Par1" } If ($Par2 -ne $Null -or $Par2 -ne '') { Write-Output "Par2 = $Par2" } If ($Par3 -ne $Null) { Write-Output "Par3 = $Par3" } } TestFunction -Par1 1 -Par3 'par3' 

... output:

 Par1 = 1 Par2 = Par3 = par3 

Although I did not pass anything to the $Par2 variable, it is still not null or empty. What happened, and how can I rewrite the instruction so that the second If statement evaluates to False and the script-block does not execute?

(I added -or $Par2 -ne '' just for verification, it behaves the same without it.)

+6
source share
1 answer

You have a logical error in your program: $Par2 will always not be equal to $null or not equal to. ''

To fix the logic, you should use -and instead of -or here:

 If ($Par2 -ne $Null -and $Par2 -ne '') { Write-Output "Par2 = $Par2" } 

However, since you $Par2 argument $Par2 in the line in the argument list of the function:

 Param ( [int]$Par1, [string]$Par2, [string]$Par3 ) ^^^^^^^^ 

checking for $Par2 -ne $Null not needed since $Par2 will always have a string of type (if you don't give it a value, it will be assigned. '' ). So you should write:

 If ($Par2 -ne '') { Write-Output "Par2 = $Par2" } 

Or, since '' evaluates to false, you can simply do:

 If ($Par2) { Write-Output "Par2 = $Par2" } 
+10
source

Source: https://habr.com/ru/post/985445/


All Articles