Basically, parameters work one of two ways. Either they work with functions, or with your script as a whole.
To define parameters for your script as a whole, place a param() block at the top of your script (or just inside the function if you’re doing function parameters):
param(
$Parameter1,
$Parameter2
)
Write-Output $Parameter1, $Parameter2
You can think of these basically like any other variable; they can be modified later, have default values, and so on. The main difference between regular variables and parameters is that anyone calling the script can freely specify the value. Here’s a quick example of how to do so, using the above example parameters:
PS C:\Path\To\> Script.ps1 -Parameter1 "Value of Parameter1" -Parameter2 -14
Value of Parameter1
-14
As you can see, even though the values were never actually specified in the Script, PS will happily pass the user’s values on in and work with them. Additionally, for parameters that need specific values, you can do validation checks. For example, if you need a number between 1 and 100, but the user enters “hello” instead, you don’t need to deal with it manually:
param(
[ValidateScript(
{ $PSItem -ge 1 -and $PSItem -le 100 }
)]
[int]
$Number
)
Write-Output "You picked the number $Number!"
Here, we define a type for the parameter. [int] accepts only whole numbers. That rules out the possibility of users entering random text. If they try, PowerShell will tell them it won’t work, and stop processing the script. We’ve also added a bit of script that checks the value to make sure it’s between 1 and 100. $PSItem, also commonly referenced as $_, refers to the ‘current value’, because that can change quite a bit. It gets used in many places, most notably things working heavily with the pipeline system. Here, it just refers to “whatever the user entered for this parameter”.
For reference, here is a pretty thoroughly specified set of attributes for a parameter:
[Parameter(Position = 0, Mandatory, ParameterSetName = "Set1")]
[Alias('P1')]
[ValidateNotNullOrEmpty()]
[string]
$Parameter1
You needn’t always specify all of them, and there are of course some I haven’t mentioned. There are a whole host of [Validate*()] attributes for different purposes.
Here’s the Microsoft documentation on advanced parameters for the full gamut:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6