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

Ryan Gillies picture Ryan Gillies · Sep 4, 2013 · Viewed 15.1k times · Source

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?

Answer

JPBlanc picture JPBlanc · Sep 4, 2013

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