How to distinguish between empty argument and zero-value argument in Powershell?

18,580

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" }
Share:
18,580
Ryan Gillies
Author by

Ryan Gillies

Updated on July 24, 2022

Comments

  • Ryan Gillies
    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
    Ryan Gillies over 10 years
    Didn't realise there was a difference between $args[0] -eq $null and !$args[0] - many thanks!
  • Michael Kargl
    Michael Kargl over 10 years
    If 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
    Rynant over 10 years
    @MichaelKargl What do you mean by "if(-1) is always false"? -1 evaluates to True (try [bool]-1). Also note that in addition to $null and 0, empty strings also evaluate to False ([bool]"")
  • Michael Kargl
    Michael Kargl over 10 years
    My bad.. typo.. its always $True as it is unequal 0.
  • yairr
    yairr over 5 years
    This 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.