I am writing a .ps1 PowerShell script, and I was wondering how I would find how many arguments the user passed. For example, I need my program to handle checking a string in multiple files. So the user should be able to type in
./Script "a" ex1.txt
or
./Script "a" ex1.txt ex2.txt
I know in Bash we can use $#
, but how do I check in PowerShell?
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:
a
b
c
Read through a few help files if you have time; they are generally very helpful!
get-help *
get-help *parameters*
get-help about_Parameters
get-help about_Automatic_Variables
get-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!
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