Mark
Mark

Reputation: 339

Empty parameter is not Null in function

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'

...the output is:

Par1 = 1
Par2 = 
Par3 = par3

Even though I didn't pass anything into the $Par2 variable, it still isn't Null or empty. What happened, and how can I rewrite the statement so that the second If-statement evaluates as False and the script-block does not get executed?

(I added the -or $Par2 -ne '' just to test, it behaves the same with and without it.)

Upvotes: 8

Views: 47441

Answers (2)

Malik Ismaeel
Malik Ismaeel

Reputation: 43

You can check that (check if $variablename has $null as value):

if (!$variablename) { Write-Host "variable is null" }

And if you wanna check if $variablename has any value except $null:

if ($variablename) { Write-Host "variable is NOT null" }

Upvotes: 1

user2555451
user2555451

Reputation:

You have a logic error in your program: $Par2 will always be not 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, because you casted the $Par2 argument to a string in the function's argument list:

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

the check for $Par2 -ne $Null is unnecessary since $Par2 will always be of type string (if you do not give it a value, it will be assigned to ''). So, you should actually write:

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

Or, because '' evaluates to false, you might just do:

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

Upvotes: 13

Related Questions