powershellif-statementnullzero

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


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?


Solution

  • 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].

    1. $args[0] -eq $null : This checks if the first argument in the $args array is equal to $null. If $args[0] is $null, it returns True; otherwise, it returns False.
    2. $null -eq $args[0] : While this performs the same logical comparison, it is generally safer to use this order. Because if $args[0] is undefined or doesn't exist it prevents PowerShell from trying to evaluate a potentially non-existent value, reducing the risk of exception.
    3. $args[0] -eq $null : This checks if $args[0] is exactly equal to null. In PowerShell, $null represents an absence of a value. If $args[0] is undefined or explicitly set to $null, this comparison returns True.
    4. $args[0] -eq 0 : This checks if $args[0] is numerically equal to 0. PowerShell treats numbers differently from $null, so this comparison only returns True if $args[0] contains the number 0. If $args[0] is $null, or is $args[0] is a string, this will return False.
    5. !$args[0] : checks for any "falsy" value, including $false, $null, 0, and an empty string.