PowerShell - how to count the number of arguments PowerShell - how to count the number of arguments powershell powershell

PowerShell - how to count the number of arguments


Within a script or function, you can access the arguments passed in via the automatically-populated $args variable. The $args is an array, so you can find the number of arguments passed via its Count property.

An example:

function PrintArgs(){    Write-Host "You passed $($args.Count) arguments:"    $args | Write-Host}

Calling PrintArgs:

> PrintArgs 'a' 'b' 'c'You passed 3 arguments:abc


Read through a few help files if you have time; they are generally very helpful!

get-help *get-help *parameters*get-help about_Parametersget-help about_Automatic_Variablesget-help about_Functions*#etc...

Notes from the help that should help you:

$Args

Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

In an event action, the $Args variable contains objects that represent the event arguments of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the SourceArgs property of the PSEventArgs object (System.Management.Automation.PSEventArgs) that Get-Event returns.

$PSBoundParameters

Contains a dictionary of the parameters that are passed to a script or function and their current values. This variable has a value only in a scope where parameters are declared, such as a script or function. You can use it to display or change the current values of parameters or to pass parameter values to another script or function.

If you end up using both bound parameters and unbound arguments, you can combine the two (example)

Slightly off topic:

I highly recommend against using $args. You should always use bound parameters, there are very few cases when you are forced to not use them.

Why? All functions that take parameters should follow best practices and use the param() block for your parameters. If you read up on parameters in the help files, you will find that using the param block gives you all sorts of helpful features, like validation, forcing mandatory params, accepting pipeline input, etc. It is also required before you let PowerShell do even more work for you with [cmdletbinding()]

Cheers!


You use the built in $Args and the property Count for it.

$Args.Count

That will give you how many arguments the user passed to the script.