PowerShell Parameters and Arguments

Parameters are the inputs a function or script accepts. Arguments are the actual values passed to those parameters when calling a function or running a script. Mastering parameters makes scripts flexible, reusable, and safe to use in automated pipelines.

Parameters vs Arguments

  function Get-Info {
      param($Name, $Age)   ← Parameters (defined in function)
  }
  
  Get-Info -Name "Riya" -Age 25  ← Arguments (values passed in)
                  |             |
              Argument      Argument

Defining Parameters with param()


function Show-UserInfo {
    param (
        $Username,
        $Department
    )
    Write-Host "User: $Username | Dept: $Department"
}

Show-UserInfo -Username "admin" -Department "IT"

Output:


User: admin | Dept: IT

Parameter Attributes

Parameter attributes control how a parameter behaves — whether it is required, what type it accepts, what position it sits in, and more.

Mandatory Parameter


function Get-Report {
    param (
        [Parameter(Mandatory=$true)]
        [string]$ReportName
    )
    Write-Host "Generating report: $ReportName"
}

# If -ReportName is not provided, PowerShell prompts for it
Get-Report -ReportName "Monthly Sales"

Optional Parameter with Default Value


function Connect-Server {
    param (
        [string]$ServerName = "localhost",
        [int]$Port          = 443
    )
    Write-Host "Connecting to $ServerName on port $Port"
}

Connect-Server                                   # Uses defaults
Connect-Server -ServerName "prod-server.com"     # Uses default port
Connect-Server -ServerName "app.server.com" -Port 8080   # Custom both

Output:


Connecting to localhost on port 443
Connecting to prod-server.com on port 443
Connecting to app.server.com on port 8080

Positional Parameters

Positional parameters allow arguments to be passed without specifying the parameter name — based on their position in the call.


function Add-Numbers {
    param (
        [Parameter(Position=0)]
        [int]$FirstNumber,

        [Parameter(Position=1)]
        [int]$SecondNumber
    )
    Write-Host "Sum: $($FirstNumber + $SecondNumber)"
}

# Named (explicit)
Add-Numbers -FirstNumber 10 -SecondNumber 20

# Positional (no parameter name needed)
Add-Numbers 10 20

Output:


Sum: 30
Sum: 30

Parameter Type Validation

Type declarations restrict what kind of value a parameter accepts.


function Get-Discount {
    param (
        [decimal]$OriginalPrice,
        [double]$DiscountPercent
    )

    $discount = $OriginalPrice * ($DiscountPercent / 100)
    $finalPrice = $OriginalPrice - $discount
    Write-Host "Discount: ₹$discount"
    Write-Host "Final Price: ₹$finalPrice"
}

Get-Discount -OriginalPrice 2000 -DiscountPercent 15

Output:


Discount: ₹300
Final Price: ₹1700

Validation Attributes

Validation attributes automatically check parameter values before the function body runs. This prevents invalid input without writing manual checks inside the function.

ValidateSet – Allow Only Specific Values


function Set-Environment {
    param (
        [ValidateSet("development", "staging", "production")]
        [string]$Environment
    )
    Write-Host "Environment set to: $Environment"
}

Set-Environment -Environment "staging"      # Works
Set-Environment -Environment "testing"      # Error – not in ValidateSet

ValidateRange – Allow Only a Number Range


function Set-Priority {
    param (
        [ValidateRange(1, 10)]
        [int]$Priority
    )
    Write-Host "Task priority: $Priority"
}

Set-Priority -Priority 5     # Works
Set-Priority -Priority 15    # Error – outside range 1-10

ValidateLength – Restrict String Length


function Set-Password {
    param (
        [ValidateLength(8, 20)]
        [string]$Password
    )
    Write-Host "Password accepted."
}

Set-Password -Password "Secure@123"     # Works (10 chars)
Set-Password -Password "abc"            # Error – too short

ValidatePattern – Match a Regex Pattern


function Set-IPAddress {
    param (
        [ValidatePattern("^\d{1,3}(\.\d{1,3}){3}$")]
        [string]$IPAddress
    )
    Write-Host "IP set to: $IPAddress"
}

Set-IPAddress -IPAddress "192.168.1.10"    # Works
Set-IPAddress -IPAddress "not-an-ip"       # Error – doesn't match pattern

ValidateNotNullOrEmpty – Block Empty Values


function Get-User {
    param (
        [ValidateNotNullOrEmpty()]
        [string]$Username
    )
    Write-Host "Fetching user: $Username"
}

Get-User -Username "admin"    # Works
Get-User -Username ""         # Error – empty string not allowed

Switch Parameters (Flag Parameters)

A switch parameter acts as a boolean flag. If passed, it is $true. If not passed, it is $false. No value needed — just include or exclude the flag.


function Get-ProcessList {
    param (
        [switch]$Verbose,
        [switch]$TopOnly
    )

    if ($TopOnly) {
        Write-Host "Showing top 5 processes by CPU:"
        Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
    } else {
        Write-Host "Showing all processes:"
        Get-Process
    }
}

# Run with -TopOnly flag
Get-ProcessList -TopOnly

# Run without flag
Get-ProcessList

Pipeline Input Parameters

Parameters can accept values directly from the pipeline using ValueFromPipeline or ValueFromPipelineByPropertyName.


function Show-Length {
    param (
        [Parameter(ValueFromPipeline=$true)]
        [string]$InputString
    )
    process {
        Write-Host "'$InputString' has $($InputString.Length) characters"
    }
}

# Call normally
Show-Length -InputString "PowerShell"

# Call via pipeline
"Hello", "World", "PowerShell" | Show-Length

Output:


'PowerShell' has 10 characters
'Hello' has 5 characters
'World' has 5 characters
'PowerShell' has 10 characters

Script Parameters ($args and param() in .ps1 Files)

When a script file (.ps1) uses parameters, they are defined the same way as in functions — using param() at the top of the file.

backup.ps1:


param (
    [Parameter(Mandatory=$true)]
    [string]$SourcePath,

    [string]$DestinationPath = "C:\Backup",

    [switch]$Compress
)

Write-Host "Backing up: $SourcePath → $DestinationPath"
if ($Compress) {
    Write-Host "Compression enabled."
}

Running the script:


# Basic run
.\backup.ps1 -SourcePath "C:\Data"

# With destination
.\backup.ps1 -SourcePath "C:\Data" -DestinationPath "D:\Backup"

# With compression flag
.\backup.ps1 -SourcePath "C:\Data" -Compress

Parameter Validation Summary Table

AttributePurposeExample
Mandatory=$trueParameter is required[Parameter(Mandatory=$true)]
Position=0Allow positional input[Parameter(Position=0)]
ValidateSetOnly allow listed values[ValidateSet("A","B","C")]
ValidateRangeOnly allow number range[ValidateRange(1,100)]
ValidateLengthRestrict string length[ValidateLength(4,20)]
ValidatePatternRegex pattern check[ValidatePattern("^\d+$")]
ValidateNotNullOrEmptyBlock null/empty input[ValidateNotNullOrEmpty()]
ValueFromPipelineAccept pipeline input[Parameter(ValueFromPipeline=$true)]

Summary

Parameters and arguments transform functions from single-use code blocks into flexible, reusable tools. Mandatory attributes force critical inputs. Default values handle optional arguments cleanly. Validation attributes block bad input before it causes problems. Switch parameters act as on/off flags. Pipeline-enabled parameters integrate functions directly into the PowerShell pipeline. Together, these features bring functions up to the same standard as built-in PowerShell cmdlets.

Leave a Comment