Empty parameter is not Null in function Empty parameter is not Null in function powershell powershell

Empty parameter is not Null in function


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" }


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" }