0
0
PowerShellscripting~5 mins

Parameters in PowerShell

Choose your learning style9 modes available
Introduction

Parameters let you give information to a script or function so it can work with different data each time.

You want to reuse a script but with different input values.
You need to make your script flexible for different tasks.
You want to avoid changing the script code every time you run it.
You want to make your script easier to understand by naming inputs clearly.
Syntax
PowerShell
param(
    [type]$ParameterName
)

Parameters are declared at the start of a script or function using param().

You can specify the type of the parameter to help catch errors early.

Examples
This script takes one string parameter called Name and prints a greeting.
PowerShell
param(
    [string]$Name
)

Write-Output "Hello, $Name!"
This script takes an integer parameter Count and prints numbers from 1 to that count.
PowerShell
param(
    [int]$Count
)

for ($i = 1; $i -le $Count; $i++) {
    Write-Output "Number $i"
}
This script has a parameter with a default value. If no value is given, it uses "default.txt".
PowerShell
param(
    [string]$FilePath = "default.txt"
)

Write-Output "Processing file: $FilePath"
Sample Program

This script takes two parameters: a user name and an age, then prints them.

PowerShell
param(
    [string]$UserName,
    [int]$Age
)

Write-Output "User Name: $UserName"
Write-Output "User Age: $Age"
OutputSuccess
Important Notes

You run the script by passing parameters like: .\script.ps1 -UserName Alice -Age 30.

If you don't provide a parameter value and no default is set, PowerShell will ask you to enter it.

Using parameters makes your scripts more reusable and easier to maintain.

Summary

Parameters let scripts accept input values to work with.

Declare parameters at the start using param().

You can set types and default values for parameters.