When first starting out writing PowerShell scripts you're not necessarily concerned about things such as modularity, reusability and "best practices." You're just getting your feet wet. However, as time goes on, you'll soon realize that you begin repeating yourself in code
You'll notice that the need to do the same thing over and over keeps getting greater. You could just copy and paste that same code, but it's not sustainable. Instead, why not create small "building blocks" in code so that they can be reused? It's time to start creating PowerShell functions.
A function in PowerShell is a grouping of code that has an optional input and output. It's a way of collecting up a bunch of code to perform one or many different times by just pointing to it instead of duplicating that code repeatedly.
Get-Time is a simple function that returns a value.
# The Get-Time function returns the current time. function Get-Time() { return Get-Date -DisplayHint Time } Get-Time
Get-Square is a simple function that accepts a parameter and returns a value based on that parameter.
# The Get-Square function returns the square (x^2) of the value provided. function Get-Square([int]$value) { $result = $value * $value return $result } $value = Read-Host 'Enter a value' $result = Get-Square $value Write-Output "$value * $value = $result"
By default, PowerShell arguments are passed by value.
function Get-ByValue($value) { "value = $value" $value = 1 "value = $value" } $x = 0 Get-ByValue $x "x = $x" # Output: # value = 0 # value = 1 # x = 0
PowerShell arguments may be passed by reference using the Ref keyword.
function Get-ByReference([ref]$ref) { "ref = " + $ref.value $ref.value = 1 "ref = " + $ref.value } $x = 0 Get-ByReference ([ref]$x) "x = $x" # Output: # ref = 0 # ref = 1 # x = 1
The $args array variable may be used to access a variable length parameter list.
function Get-Args() { foreach($arg in $args) { $arg } } Get-Args 1 2 3 4
By default, PowerShell arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
function Show-Parameters($name, $number) { "Name = $name, Number = $number" } Show-Parameters '1' 'Wiki' Show-Parameters -number '1' -name 'Wiki' # Output: # Name = 1, Number = Wiki # Name = Wiki, Number = 1
By default, variables are available only in the scope in which they are created.
function Show-FunctionScope() { $x = 1 "function x = $x" } $x = 0 Show-FunctionScope "script x = $x" # Output: # function x = 1 # script x = 0
You can use a scope modifier to change the scope of a variable.
function Show-ScriptScope() { $x = 1 "function x = $x" $script:x = 2 } $x = 0 Show-ScriptScope "script x = $x" # Output: # function x = 1 # script x = 2
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
# The Get-Factorial function returns the factorial of the value provided using recursion. function Get-Factorial([int]$value) { if($value -lt 0) { $result = 0 } elseif($value -le 1) { $result = 1 } else { $result = $value * (Get-Factorial($value - 1)) } return $result } $value = Read-Host 'Enter a value' $result = Get-Factorial $value Write-Output "$value! = $result"
function Get-Square() { Param ( [double]$value ) return $value * $value }
The Mandatory argument indicates that the parameter is required.
function Get-Square() { Param ( [parameter(Mandatory=$true)] [double]$value ) return $value * $value }
The ValidateRange attribute specifies a numeric range for each parameter or variable value.
function Get-Square() { Param ( [parameter(Mandatory=$true)] [ValidateRange(1,10)] [double]$value ) return $value * $value }
The ValidateNotNullOrEmpty attribute specifies that the parameter value cannot be null ($null) and cannot be an empty string ("").
function Get-Posessive() { Param ( [parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$value ) if($value.Substring($value.Length - 1, 1) -eq 's') { $result = $value + '''' } else { $result = $value + '''s' } return $result }
The ValidateLength attribute specifies the minimum and maximum number of characters in a parameter or variable value.
function Check-ZipCode() { Param ( [parameter(Mandatory=$true)] [ValidateLength(5,5)] [string]$value ) return $value }
The ValidatePattern attribute specifies a regular expression that is compared to the parameter or variable value.
function Check-ZipCode() { Param ( [parameter(Mandatory=$true)] [ValidatePattern('^\d{5}$|^\d{5}-\d{4}$')] [string]$value ) return $value }
The ValidateScript attribute specifies a script that is used to validate a parameter or variable value.
function Get-Reciprocal() { Param ( [parameter(Mandatory=$true)] [ValidateScript({$_ -ne 0})] [double]$value ) return 1 / $value }