Code Reference

Functions

PowerShell · Reference cheat sheet

Functions

PowerShell · Reference cheat sheet


📋 Overview

Functions encapsulate reusable logic. Advanced functions use [CmdletBinding()] to gain common parameters, pipeline binding, and -WhatIf support. Prefer Verb-Noun names and explicit param() blocks.

🔧 Core concepts

FeatureDetail
Simplefunction Name \{ param(...) … \}
Advanced[CmdletBinding()] + param attributes
PipelineValueFromPipeline, process \{\}
OutputWrite objects; avoid Write-Host for data
ScopeFunctions see parent scope unless local
Dynamic paramsAdvanced scenarios
Comment-based help.SYNOPSIS in comments

Blocks: begin, process, end, clean (PS 7.3+). Use process for pipeline streaming.

💡 Examples

Advanced function:

function Get-FileSizeMb {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
    [Alias('FullName')]
    [string]$Path
  )
  process {
    $item = Get-Item -LiteralPath $Path
    [pscustomobject]@{
      Path = $item.FullName
      SizeMB = [math]::Round($item.Length / 1MB, 2)
    }
  }
}

Get-ChildItem *.log | Get-FileSizeMb

ShouldProcess:

function Remove-OldLog {
  [CmdletBinding(SupportsShouldProcess)]
  param([string]$Path)
  if ($PSCmdlet.ShouldProcess($Path, 'Remove')) {
    Remove-Item -LiteralPath $Path
  }
}

⚠️ Pitfalls

  • Write-Host bypasses the pipeline—use Write-Output / implicit output for data.
  • Forgetting process \{\} breaks per-object pipeline behavior (only runs once).
  • $args is unstructured—prefer param().
  • Name collisions with cmdlets: use a module prefix or approved verbs.
  • Returning arrays may get flattened—use Write-Output -NoEnumerate or unary comma when needed.
  • Don’t use exit inside library functions; throw or return instead.

On this page