Powershell - Function

About

Grammar - Function in Powershell

A function is a special type of command.

Syntax

function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]  
{
  param([type]$parameter1 [,[type]$parameter2])

  dynamicparam {<statement list>}

  begin {<statement list>}
  process {<statement list>}
  end {<statement list>}
}

Simple

function <function-name> {statements}

Example: finds all .jpg files in the current user's directories that were changed after the start date.

function Get-NewPix
{
  $start = get-date -month 1 -day 1 -year 2010
  $allpix = get-childitem -path $env:userprofile\* -include *.jpg -recurse
  $allpix | where {$_.lastwritetime -gt $start}
}   

Param

Definition

function md5sum {
    param
    (
        [Parameter(Mandatory=$true, HelpMessage='The file containing the hash.')]
        [string]$file
    ) 
    echo "Checking if required packages are present and valid..."
    foreach ($line in (Get-Content $file)) {
       ................
    }
}

md5sum -file checksum.txt

Check

If the parameters is not mandatory, you can check if it's passed with the following command

if (!($PSBoundParameters.ContainsKey('file'))){
	Write-Host "The (file) parameter was not given"
} else {
	Write-Host "The (file) parameter was given"
}

Return

Same behavior than bash: All output is captured, and returned

This syntax are the same:

$a
return
# is equivalent to
return $a

About return

Management

List

Get-Command -CommandType Function

Write

about_Functions: Describes how to create and use functions in Windows PowerShell

get-help about_Functions

About function

Help

get-help function-name

More ..

  • Command based

To create comment-based help for a function, the comments must be placed at the beginning or end of the function body or on the lines preceding the function keyword. get-help about_Comment_Based_Help

# Comment-Based Help  for Functions

Powered by ComboStrap