Learn › PowerShell

PowerShell Scripts and Functions with Parameters

Turn your commands into reusable .ps1 scripts and functions with parameters, validation, help text and pipeline input – so others can run them safely.

Intermediate 11 min read
By Gopinath Karthikeyan

A good script is one someone else can run without asking you how. Parameters, validation and built-in help make that possible. This guide turns a one-liner into a proper tool.

From one-liner to script

Save this as Get-DiskReport.ps1:

param(
    [string[]] $ComputerName = $env:COMPUTERNAME,
    [int] $WarnPercent = 15
)

foreach ($c in $ComputerName) {
    Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $c |
        Select-Object @{n='Server';e={$c}}, DeviceID,
            @{n='FreePct';e={[math]::Round($_.FreeSpace/$_.Size*100)}} |
        Where-Object FreePct -lt $WarnPercent
}

Run it:

.\Get-DiskReport.ps1 -ComputerName SRV01, SRV02 -WarnPercent 20

Functions

A function is a named block you can call many times. The best ones look and behave like built-in cmdlets:

function Get-DiskReport {
    <#
    .SYNOPSIS
        Lists fixed disks below a free-space threshold.
    .EXAMPLE
        Get-DiskReport -ComputerName SRV01 -WarnPercent 20
    #>
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string[]] $ComputerName = $env:COMPUTERNAME,

        [ValidateRange(1, 99)]
        [int] $WarnPercent = 15
    )

    process {
        foreach ($c in $ComputerName) {
            Write-Verbose "Checking $c"
            Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $c |
                ForEach-Object {
                    [pscustomobject]@{
                        Server  = $c
                        Drive   = $_.DeviceID
                        FreePct = [math]::Round($_.FreeSpace / $_.Size * 100)
                    }
                } | Where-Object FreePct -lt $WarnPercent
        }
    }
}

What each part gives you:

Part Benefit
Comment-based help (<# .SYNOPSIS #>) Get-Help Get-DiskReport -Examples works
[CmdletBinding()] Adds -Verbose, -ErrorAction and other common parameters for free
Types ([int], [string[]]) Wrong input fails early with a clear message
[ValidateRange], [ValidateSet('A','B')], [ValidateNotNullOrEmpty()] Stops bad values before anything runs
ValueFromPipeline + process {} Get-Content servers.txt | Get-DiskReport works
Returning objects Callers can sort, filter and export the result

Mandatory parameters

param(
    [Parameter(Mandatory)]
    [string] $ServerName
)

PowerShell prompts if it’s missing. For passwords, use [pscredential] or [securestring] – never a plain string.

Switches

param([switch] $IncludeHealthy)
if ($IncludeHealthy) { ... }

Run with -IncludeHealthy to turn it on.

Dot-sourcing vs scripts

  • Run a script: .\Get-DiskReport.ps1 -WarnPercent 20
  • Load its functions into your session: . .\Tools.ps1 (note the dot and space), then call Get-DiskReport.
  • For many functions, build a module – see Build a module and safe automation patterns.

Style that helps the next person

  • Approved verbs only (Get-Verb lists them) so names are predictable.
  • One function, one job.
  • Write-Verbose for progress details; Write-Warning for problems; avoid Write-Host for data.
  • No hard-coded server names, paths or passwords – make them parameters.

FAQ

Why return objects instead of printing nice text? Text can only be read. Objects can be sorted, filtered, exported, emailed or passed to the next command.

What’s next

Next: Error handling and logging.

Practise this topic

Test yourself with free questions on this topic – instant answers and explanations.

Start practice questions

PowerShellScriptingFunctionsIntermediate

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn

More in PowerShell