How to distinguish between empty argument and zero-value argument in Powershell?
Solution 1
You can just test $args
variable or $args.count
to see how many vars are passed to the script.
Another thing $args[0] -eq $null
is different from $args[0] -eq 0
and from !$args[0]
.
Solution 2
If the variable is declared in param()
as an integer then its value will be '0' even if no value is specified for the argument. To prevent that you have to declare it as nullable:
param([AllowNull()][System.Nullable[int]]$Variable)
This will allow you to validate with If ($Variable -eq $null) {}
Solution 3
If users like me come from Google and want to know how to treat empty command line parameters, here is a possible solution:
if (!$args) { Write-Host "Null" }
This checks the $args array. If you want to check the first element of the array (i.e. the first cmdline parameter), use the solution from the OP:
if (!$args[0]) { Write-Host "Null" }
Ryan Gillies
Updated on July 24, 2022Comments
-
Ryan Gillies almost 2 years
I want to be able to pass a single int through to a powershell script, and be able to tell when no variable is passed. My understanding was that the following should identify whether an argument is null or not:
if (!$args[0]) { Write-Host "Null" } else { Write-Host "Not null" }
This works fine until I try to pass 0 as an int. If I use 0 as an argument, Powershell treats it as null. Whats the correct way to be able to distinguish between the argument being empty or having a zero value?
-
Ryan Gillies over 10 yearsDidn't realise there was a difference between
$args[0] -eq $null
and!$args[0]
- many thanks! -
Michael Kargl over 10 yearsIf you use the $Var directly in a condition it evaluates everything that is $Null or 0 to $False.. everything else to $True. So If(-1) is always False.
-
Rynant over 10 years@MichaelKargl What do you mean by "if(-1) is always false"?
-1
evaluates toTrue
(try[bool]-1
). Also note that in addition to$null
and0
, empty strings also evaluate toFalse
([bool]""
) -
Michael Kargl over 10 yearsMy bad.. typo.. its always $True as it is unequal 0.
-
yairr over 5 yearsThis answer would be a lot better if it explained the differences between the equality checks. As it is I hear they are different, but I have no idea why. It should tell me how to properly check for empty/null/zero arguments.