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

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


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


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) {}


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