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?
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 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) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With