Add parameters to PowerShell Script

If you want to add parameters to your PowerShell Script you have to define them. In this defintion you also specify the data type. A simple example to get the idea:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# definition of parameters
Param(
    [string]$StringParameter,
    [bool]$BooleanParameter = $False,
    [int]$IntegerParameter = 10,
    [switch]$SwitchParameter
)

# output of the parameter values
Write-host "StringParameter: $StringParameter"
Write-host "BooleanParameter: $BooleanParameter"
Write-host "IntegerParameter: $IntegerParameter"
Write-host "SwitchParameter: $SwitchParameter"

Several parameters are defined with a comma between them, there is no comma after the last one. You can also define default values (lines 4 and 5 in the example script). If you call the script and add a parameter the corresponding default value is overwritten. Instead of the data type boolean you can also use switch. If you use switch the variable is “true” as soon as the parameter is added (you can use “-SwitchParameter” instead of “-SwitchParameter:$True”).

See an execution of the script above and its output:

PS C:\> .\PowerShellParameter.ps1 -StringParameter "Text" -BooleanParameter $True
StringParameter: Text
BooleanParameter: True
IntegerParameter: 10
SwitchParameter: False

You can also specify that some parameters are mandatory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# definition of parameters
Param(
    [Parameter(Mandatory=$True)]
    [string]$StringParameter,

    [Parameter(Mandatory=$False)]
    [bool]$BooleanParameter = $False,

    [Parameter(Mandatory=$False)]
    [int]$IntegerParameter = 10,

    [Parameter(Mandatory=$False)]
    [switch]$SwitchParameter
)

# output of the parameter values
Write-host "StringParameter: $StringParameter"
Write-host "BooleanParameter: $BooleanParameter"
Write-host "IntegerParameter: $IntegerParameter"
Write-host "SwitchParameter: $SwitchParameter"

“(Mandatory=$True)” sets the parameter “$StringParameter” to madatory (line 3). With “$False” its up to you if you add the parameter to your script call. Parameters who are not mandatory should have a default value defined (line 7 and 10).

If you don’t add the parameter “$StringParameter” to the call of the example script, PowerShell aks for a value:

PS C:\> .\PowerShellParameter.ps1 -BooleanParameter $True

cmdlet PowerShellParameter.ps1 at command pipeline position 1
Supply values for the following parameters:
StringParameter: