Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 501
Ryan Gillies Avatar asked Sep 04 '13 07:09

Ryan Gillies


3 Answers

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

like image 59
JPBlanc Avatar answered Oct 18 '22 01:10

JPBlanc


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" }
like image 25
Timo Avatar answered Oct 18 '22 00:10

Timo


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

like image 2
TheDude Avatar answered Oct 17 '22 23:10

TheDude