Question

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?

Était-ce utile?

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

Autres conseils

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

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top