Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check number of arguments in PowerShell?

Tags:

powershell

param (
[string]$Name =  $args[0],#First argument will be the adapter name
[IPAddress]$IP = $args[1],#Second argument will be the IP address
[string]$InterfaceId = $args[3],#Second argument will be the IP address
[string]$VlanId = $args[4], #Fourth argument will be vlanid
[string]$SubnetIP = $args[5],#subnet mask
[string]$IPType = "IPv4",
[string]$Type = "Static"
)
Write-Host $Args.Count

I want to check if commandline arguments are supplied to a PowerShell script or not and if it is not supplied I want to show a usage information.

I am running the script in admin mode. I found one method that uses $Args.Count. It seems as it can get the arguments count while running the script but it is always zero for me.

What am I doing wrong?

enter image description here

like image 502
wahab Mohmadsharif Avatar asked Oct 19 '25 09:10

wahab Mohmadsharif


1 Answers

Get rid of the $args[x] assignments and add [cmdletbinding()] on top.

[CmdLetbinding()]
param (
[string]$Name, #First argument will be the adapter name
[IPAddress]$IP, # etc...
[string]$InterfaceId,
[string]$VlanId,
[string]$SubnetIP,
[string]$IPType = "IPv4",
[string]$Type = "Static"
)

Then you can use $PSBoundParameters.Count to get the argument count.

$args is a special variable that is used when named parameter are not present. Therefore, since you have named parameter, it will always give you a count of zero (except maybe if you add more arguments than there is named parameters)

If you use a param block, then you don't need to assign $args[0] and others. In fact, this is totally useless as they will be $null.

The other approach, although I recommend you to keep the param block, is to not use any named parameters at all. In that case, $args will work as you expect it to.

[string]$Name =  $args[0]
[IPAddress]$IP = $args[1]
[string]$InterfaceId = $args[3]
[string]$VlanId = $args[4] 
[string]$SubnetIP = $args[5]
[string]$IPType = "IPv4"
[string]$Type = "Static"

The main difference is that if you have a param block, you can call your script in the following ways:

  1. .\MyScript.ps1 -Name "Hello" -Ip 127.0.0.1
  2. .\MyScript.ps1 "Hello" 127.0.0.1

Without the param block, you have only option #2 available to call the script.

like image 120
Sage Pourpre Avatar answered Oct 22 '25 03:10

Sage Pourpre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!