Multiple Values on a Parameter in PowerShell

  1. Understanding the Parameter Function in PowerShell
  2. Use the Named Parameters in PowerShell
  3. Using Defaults to a Parameter in PowerShell
  4. Using Switch Parameters in PowerShell
  5. Use the Mandatory Parameters in PowerShell
  6. Using an Unknown Number of Arguments in PowerShell
  7. Using the Pipeline Parameters in PowerShell
Multiple Values on a Parameter in PowerShell

We handle arguments using the PowerShell parameter function param. It is a fundamental component of any script, enabling developers to provide input at runtime.

In addition, if a script’s behavior needs to change, a parameter can offer an opportunity to do so without changing the underlying code.

This article will discuss the parameter function, different variables that we can define, handle multiple values in a single parameter, and sample uses.

Understanding the Parameter Function in PowerShell

Administrators can create parameters for scripts using the parameter function param().

Inside, the parameter function contains one or more parameters defined by variables.

param ($myVariable)

However, to ensure that the parameter accepts only the type of input you need, it is best to assign a data type to the parameter by enclosing the data type with square brackets [] before the variable.

param ([String]$myVariable)

We can then use the named parameters when executing a .ps1 file.

powershell.exe .\sample.ps1 -name "John"

Using Defaults to a Parameter in PowerShell

We can pre-assign a default value to a parameter by giving the parameter a value inside of the script.

In addition, executing the script without passing values from the command line will take the default variable defined inside the script.

param ([String]$name = "John")

Using Switch Parameters in PowerShell

We can use another parameter type for our scripts: the switch parameter defined by the [switch] data type.

This parameter is mainly used for binary or Boolean values that we have discussed before, indicating the value of true or false.

param ([switch]$isEnabled)

Example Code:

"This string is from the pipeline." | .\pipeline.ps1

Output:

This string is from the pipeline.

Doing this technique opens up many opportunities for running chained PowerShell files.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn