A block of code may be contained within a function for easy re-use.
To create a function, call the function keyword followed by a name for the function, then include your code inside a pair of curly braces.

function Add-Numbers
 $args[0] + $args[1]

PS C:\> Add-Numbers 5 10

A similar function with named parameters:

function Output-SalesTax
 param( [int]$Price, [int]$Tax )
 $Price + $Tax

PS C:\> Output-SalesTax -price 1000 -tax 38

To display the definition of a function several methods can be used:

cat function:Add-Numbers
(get-command Add-Numbers).definition

To list all functions in the current session: get-command -CommandType function

N.B in a block of code you need to define the function before you call it.

Don't add brackets around the function parameters:

$result = Add-Numbers (5, 10) --Wrong!
$result = Add-Numbers 5 10    --Right

PowerShell does not save functions or filters permanently by default. So if you close and reopen PowerShell, the function/filter will no longer be available. To make it permanent, add the function to your PowerShell $Profile file.

When you call the function name, the code within the function will run, A function can accept imported values either as arguments or through the pipeline. If the function returns any values, they can be assigned to variables or passed to other functions or cmdlets.

Function or Filter definition:

function [scope_type:]name
  [ param(param_list) ]
filter [scope_type:]name
  [ param(param_list) ]

The difference between a filter function and a regular function is the way they handle items passed through the pipeline:

With a regular function, pipeline objects are bound to the $input automatic variable, and execution is blocked until all input is received. The function then begins processing the data.

With a filter function, data is processes while it is being received, without waiting for all input. A filter receives each object from the pipeline through the $_ automatic variable, and the script block is processed for each object.

The param_list is an optional list of comma separated parameter names, these may also be preceded by their data types in brackets. This makes the function more readable than using $args and also gives you the option to supply default values.

Advanced function

An Advanced PowerShell function contains the [cmdletbinding()] attribute (or the Parameter attribute). This adds several capabilities such as additional parameter checking, and the ability to easily use Write-Verbose.
A function with cmdletbinding will throw an error if unhandled parameter values appear on the command line.

Advanced PowerShell functions typically include Begin..Process..End blocks for processing the input data, documentation and auto-help, including the parameters.

Variable Scope

By default, all variables created in functions are local, they only exist within the function, though they are still visible if you call a second function from within the first one.

To persist a variable, so the function can be called repeatedly and the variable will retain it's last value, prepend $script: to the variable name, e.g. $script:myvar

To make a variable global prepend $global: to the variable name, e.g. $global:myvar

Example Functions

A function to find all files on the C: drive owned by a particular user:

 function Get-ByOwner
   Get-ChildItem -recurse C:\ | get-acl | where {$_.Owner -match $args[0]} 

PS C:\> Get-ByOwner JackFrost

A function to display PowerShell help on, this will launch your default web browser:

 function Get-Help2
param([string]$command) Start-process -filepath "$command.html" }

You can then do:
PS C:\> Get-Help2 -command set-acl

or because there is only one parameter:
PS C:\> Get-Help2 set-acl

A filter to display only files smaller than a given size:

 filter FileSizeBelow($size) { if ($_.length -le $size) { $_ } }

PS C:\> gci \\server64\workgroups -filter | FileSizeBelow 200kb
PS C:\> gci -recurse \\server64\workgroups | ?{!$_.PSIsContainer} | FileSizeBelow 100mb

A function with default values:

 function write-price
  param([string]$description = "unknown",
        [int]$price = 100)
  Write-Output "$description ..... $price"

PS C:\> write-price -price 250 -description Hammer
Hammer ..... 250

A filter to find files owned by a specific user:

 filter ownedbyme
  if ($_.Owner -match "JackFrost") {$_}

PS C:\> gci -recurse C:\ | Get-Acl | where {$_ | ownedbyme}

“The function of the imagination is not to make strange things settled, so much as to make settled things strange” ~ G. K. Chesterton


Advanced functions - include cmdlet features, common parameters -verbose, -whatif, -confirm etc.
New-Alias - Create a new (short) alias name for your function.
Begin..Process..End - Function Input Processing
Scriptblock - A collection of statements
Ref vars - Passing a reference variable to a function.

Copyright © 1999-2017
Some rights reserved