This post will explain the procedure to resolve the mentioned query.
How to Pass an Argument to a PowerShell Script?
These methods can be used to pass an argument:
Method 1: the “param” Statement to Pass an Argument to a PowerShell Script
The first method to pass an argument to a PowerShell is using the “param” statement. It can be passed directly to the script with the help of the inverted commas or by referring to the function parameter.
The below-stated examples will practically demonstrate the given concept.
Example 1: Pass the Argument Directly to the Script Using the Inverted Commas
Check out the given script:
param($Name, $Gender)
"$Name is a $Gender"
}
Test1 "John" "Boy"
In the above script:
- First, create a function named “Test1”.
- In the function definition, use the “param” statement having the stated parameters.
- After that, display the stated message via the passed parameters.
- Finally, invoke the function by passing the stated values as its (function) arguments:
Output
The output verifies that the arguments have been passed to a PowerShell script.
Example 2: Pass the Argument to the Script by Referring to the Function Parameter
Now, let’s pass the values using the dash parameter. In the dash parameter, write the variable name with “dash –” at the start, and then specify the value which you want to pass to the argument:
param($pet, $trait)
"$pet is $trait"
}
Test2 -pet Cat -trait beautiful
In the above code snippet:
- Likewise, declare a function named “Test2”.
- In its definition, similarly, specify the stated parameters and the message.
- Lastly, access the function by referring to the function parameters along with the passed arguments, respectively:
Output
Method 2: Passing an Argument to a PowerShell Script Using the “args” Array
Another method for passing an argument to a PowerShell is utilizing the “args[ ]” array. This array refers to a specific argument.
Example
In this example, we will demonstrate the working of the “args[ ]” array:
In the above lines of code:
- Define a function named “Test3”.
- In the function definition, specify the stated parameters and assign them an array of indexed arguments specified as “$args”.
- Lastly, invoke the defined function by passing the stated values as its argument:
Output
The output shows that the arguments have been successfully passed to a PowerShell script.
Conclusion
An argument can be passed to a PowerShell script using the “param” statement or the “args[ ]” array. The former approach can be applied to pass the function arguments directly. The latter approach can be utilized to allocate the function parameters as an array of arguments and invoke the function accordingly. This article has explained a complete guide to passing an argument to a PowerShell script.