about_Functions - PowerShell (2024)

  • Article

Short description

Describes how to create and use functions in PowerShell.

Long description

A function is a list of PowerShell statements that has a name that you assign.When you run a function, you type the function name. The statements in the listrun as if you had typed them at the command prompt.

Functions can be as simple as:

function Get-PowerShellProcess { Get-Process pwsh }

Once a function is defined, you can use it like the built-in cmdlets. Forexample, to call the newly defined Get-PowerShellProcess function:

Get-PowerShellProcess
 NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 110 78.72 172.39 10.62 10936 1 pwsh

A function can also be as complex as a cmdlet or an application.

Like cmdlets, functions can have parameters. The parameters can be named,positional, switch, or dynamic parameters. Function parameters can be read fromthe command line or from the pipeline.

Functions can return values that can be displayed, assigned to variables, orpassed to other functions or cmdlets. You can also specify a return value usingthe return keyword. The return keyword doesn't affect or suppress otheroutput returned from your function. However, the return keyword exits thefunction at that line. For more information, see about_Return.

The function's statement list can contain different types of statement listswith the keywords begin, process, end, and clean. These statement listshandle input from the pipeline differently.

The filter keyword is used to create a type of function that runs on eachobject in the pipeline. A filter resembles a function with all its statementsin a process block.

Functions can also act like cmdlets. You can create a function that works justlike a cmdlet without using C# programming. For more information, seeabout_Functions_Advanced.

Important

Within script files and script-based modules, functions must be definedbefore they can be called.

Syntax

The following are the syntax for a function:

function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]{ begin {<statement list>} process {<statement list>} end {<statement list>} clean {<statement list>}}
function [<scope:>]<name>{ param([type]$parameter1 [,[type]$parameter2]) dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} clean {<statement list>}}

A function includes the following items:

  • A function keyword
  • A scope (optional)
  • A name that you select
  • Any number of named parameters (optional)
  • One or more PowerShell commands enclosed in braces {}

For more information about the dynamicparam keyword and dynamic parameters infunctions, see about_Functions_Advanced_Parameters.

Input processing methods

The methods described in this section are referred to as the input processingmethods. For functions, these three methods are represented by the begin,process, and end blocks of the function. PowerShell 7.3 adds a cleanblock process method.

You aren't required to use any of these blocks in your functions. If you don'tuse a named block, then PowerShell puts the code in the end block of thefunction. However, if you use any of these named blocks, or define adynamicparam block, you must put all code in a named block.

The following example shows the outline of a function that contains a beginblock for one-time preprocessing, a process block for multiple recordprocessing, and an end block for one-time post-processing.

Function Test-ScriptCmdlet{[CmdletBinding(SupportsShouldProcess=$True)] Param ($Parameter1) begin{} process{} end{}}

begin

This block is used to provide optional one-time preprocessing for the function.The PowerShell runtime uses the code in this block once for each instance ofthe function in the pipeline.

process

This block is used to provide record-by-record processing for the function. Youcan use a process block without defining the other blocks. The number ofprocess block executions depends on how you use the function and what inputthe function receives.

The automatic variable $_ or $PSItem contains the current object in thepipeline for use in the process block. The $input automatic variablecontains an enumerator that's only available to functions and script blocks.For more information, see about_Automatic_Variables.

  • Calling the function at the beginning, or outside of a pipeline, executes theprocess block once.
  • Within a pipeline, the process block executes once for each input objectthat reaches the function.
  • If the pipeline input that reaches the function is empty, the process blockdoes not execute.
    • The begin, end, and clean blocks still execute.

Important

If a function parameter is set to accept pipeline input, and a processblock isn't defined, record-by-record processing will fail. In this case,your function will only execute once, regardless of the input.

end

This block is used to provide optional one-time post-processing for thefunction.

clean

The clean block was added in PowerShell 7.3.

The clean block is a convenient way for users to clean up resources that spanacross the begin, process, and end blocks. It's semantically similar to afinally block that covers all other named blocks of a script function or ascript cmdlet. Resource cleanup is enforced for the following scenarios:

  1. when the pipeline execution finishes normally without terminating error
  2. when the pipeline execution is interrupted due to terminating error
  3. when the pipeline is halted by Select-Object -First
  4. when the pipeline is being stopped by Ctrl+c orStopProcessing()

The clean block discards any output that's written to the Success stream.

Caution

Adding the clean block is a breaking change. Because clean is parsed as akeyword, it prevents users from directly calling a command named clean asthe first statement in a script block. However, it's not likely to be aproblem. The command can still be invoked using the call operator(& clean).

Simple functions

Functions don't have to be complicated to be useful. The simplest functionshave the following format:

function <function-name> {statements}

For example, the following function starts PowerShell with the Run asAdministrator option.

function Start-PSAdmin {Start-Process PowerShell -Verb RunAs}

To use the function, type: Start-PSAdmin

To add statements to the function, type each statement on a separate line, oruse a semicolon ; to separate the statements.

For example, the following function finds all .jpg files in the currentuser'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\*.jpg -Recurse $allpix | Where-Object {$_.LastWriteTime -gt $Start}}

You can create a toolbox of useful small functions. Add these functions to yourPowerShell profile, as described in about_Profiles and later in thistopic.

Function Names

You can assign any name to a function, but functions that you share with othersshould follow the naming rules that have been established for all PowerShellcommands.

Functions names should consist of a verb-noun pair where the verb identifiesthe action that the function performs and the noun identifies the item on whichthe cmdlet performs its action.

Functions should use the standard verbs that have been approved for allPowerShell commands. These verbs help us to keep our command names consistentand easy for users to understand.

For more information about the standard PowerShell verbs, seeApproved Verbs.

Functions with Parameters

You can use parameters with functions, including named parameters, positionalparameters, switch parameters, and dynamic parameters. For more informationabout dynamic parameters in functions, seeabout_Functions_Advanced_Parameters.

Named Parameters

You can define any number of named parameters. You can include a default valuefor named parameters, as described later in this topic.

You can define parameters inside the braces using the param keyword, as shownin the following sample syntax:

function <name> { param ([type]$parameter1 [,[type]$parameter2]) <statement list>}

You can also define parameters outside the braces without the Param keyword,as shown in the following sample syntax:

function <name> [([type]$parameter1[,[type]$parameter2])] { <statement list>}

Below is an example of this alternative syntax.

function Add-Numbers([int]$one, [int]$two) { $one + $two}

While the first method is preferred, there is no difference between these twomethods.

When you run the function, the value you supply for a parameter is assigned toa variable that contains the parameter name. The value of that variable can beused in the function.

The following example is a function called Get-SmallFiles. This function hasa $Size parameter. The function displays all the files that are smaller thanthe value of the $Size parameter, and it excludes directories:

function Get-SmallFiles { Param($Size) Get-ChildItem $HOME | Where-Object { $_.Length -lt $Size -and !$_.PSIsContainer }}

In the function, you can use the $Size variable, which is the name defined forthe parameter.

To use this function, type the following command:

Get-SmallFiles -Size 50

You can also enter a value for a named parameter without the parameter name.For example, the following command gives the same result as a command thatnames the Size parameter:

Get-SmallFiles 50

To define a default value for a parameter, type an equal sign and the valueafter the parameter name, as shown in the following variation of theGet-SmallFiles example:

function Get-SmallFiles ($Size = 100) { Get-ChildItem $HOME | Where-Object { $_.Length -lt $Size -and !$_.PSIsContainer }}

If you type Get-SmallFiles without a value, the function assigns 100 to$size. If you provide a value, the function uses that value.

Optionally, you can provide a brief help string that describes the defaultvalue of your parameter, by adding the PSDefaultValue attribute to thedescription of your parameter, and specifying the Help property ofPSDefaultValue. To provide a help string that describes the default value(100) of the Size parameter in the Get-SmallFiles function, add thePSDefaultValue attribute as shown in the following example.

function Get-SmallFiles { param ( [PSDefaultValue(Help = '100')] $Size = 100 ) Get-ChildItem $HOME | Where-Object { $_.Length -lt $Size -and !$_.PSIsContainer }}

For more information about the PSDefaultValue attribute class, seePSDefaultValue Attribute Members.

Positional Parameters

A positional parameter is a parameter without a parameter name. PowerShell usesthe parameter value order to associate each parameter value with a parameter inthe function.

When you use positional parameters, type one or more values after the functionname. Positional parameter values are assigned to the $args array variable.The value that follows the function name is assigned to the first position inthe $args array, $args[0].

The following Get-Extension function adds the .txt filename extension to afilename that you supply:

function Get-Extension { $name = $args[0] + ".txt" $name}
Get-Extension myTextFile
myTextFile.txt

Switch Parameters

A switch is a parameter that doesn't require a value. Instead, you type thefunction name followed by the name of the switch parameter.

To define a switch parameter, specify the type [switch] before the parametername, as shown in the following example:

function Switch-Item { param ([switch]$on) if ($on) { "Switch on" } else { "Switch off" }}

When you type the On switch parameter after the function name, the functiondisplays Switch on. Without the switch parameter, it displays Switch off.

Switch-Item -on
Switch on
Switch-Item
Switch off

You can also assign a Boolean value to a switch when you run the function,as shown in the following example:

Switch-Item -on:$true
Switch on
Switch-Item -on:$false
Switch off

Using Splatting to Represent Command Parameters

You can use splatting to represent the parameters of a command. This feature isintroduced in Windows PowerShell 3.0.

Use this technique in functions that call commands in the session. You don'tneed to declare or enumerate the command parameters, or change the functionwhen command parameters change.

The following sample function calls the Get-Command cmdlet. The command uses@Args to represent the parameters of Get-Command.

function Get-MyCommand { Get-Command @Args }

You can use all the parameters of Get-Command when you call theGet-MyCommand function. The parameters and parameter values are passed to thecommand using @Args.

Get-MyCommand -Name Get-ChildItem
CommandType Name ModuleName----------- ---- ----------Cmdlet Get-ChildItem Microsoft.PowerShell.Management

The @Args feature uses the $Args automatic parameter, which representsundeclared cmdlet parameters and values from remaining arguments.

For more information, see about_Splatting.

Piping Objects to Functions

Any function can take input from the pipeline. You can control how a functionprocesses input from the pipeline using begin, process, end, and cleankeywords. The following sample syntax shows these keywords:

The process statement list runs one time for each object in the pipeline.While the process block is running, each pipeline object is assigned to the$_ automatic variable, one pipeline object at a time.

The following function uses the process keyword. The function displaysvalues from the pipeline:

function Get-Pipeline{ process {"The value is: $_"}}1,2,4 | Get-Pipeline
The value is: 1The value is: 2The value is: 4

If you want a function that can take pipeline input or input from a parameter,then the process block needs to handle both cases. For example:

function Get-SumOfNumbers { param ( [int[]]$Numbers ) begin { $retValue = 0 } process { if ($null -ne $Numbers) { foreach ($n in $Numbers) { $retValue += $n } } else { $retValue += $_ } } end { $retValue }}PS> 1,2,3,4 | Get-SumOfNumbers10PS> Get-SumOfNumbers 1,2,3,410

When you use a function in a pipeline, the objects piped to the function areassigned to the $input automatic variable. The function runs statements withthe begin keyword before any objects come from the pipeline. The functionruns statements with the end keyword after all the objects have been receivedfrom the pipeline.

The following example shows the $input automatic variable with begin andend keywords.

function Get-PipelineBeginEnd { begin { "Begin: The input is $input" } end { "End: The input is $input" }}

If this function is run using the pipeline, it displays the followingresults:

1,2,4 | Get-PipelineBeginEnd
Begin: The input isEnd: The input is 1 2 4

When the begin statement runs, the function doesn't have the input from thepipeline. The end statement runs after the function has the values.

If the function has a process keyword, each object in $input is removedfrom $input and assigned to $_. The following example has a processstatement list:

function Get-PipelineInput{ process {"Processing: $_ " } end {"End: The input is: $input" }}

In this example, each object that's piped to the function is sent to theprocess statement list. The process statements run on each object, oneobject at a time. The $input automatic variable is empty when the functionreaches the end keyword.

1,2,4 | Get-PipelineInput
Processing: 1Processing: 2Processing: 4End: The input is:

For more information, see Using Enumerators

PowerShell 7.3 added the clean block. The clean block is a convenient wayfor users to clean up resources created and used in the begin, process, andend blocks. It's semantically similar to a finally block that covers allother named blocks of a script function or a script cmdlet. Resource cleanup isenforced for the following scenarios:

  1. when the pipeline execution finishes normally without terminating error
  2. when the pipeline execution is interrupted due to terminating error
  3. when the pipeline is halted by Select-Object -First
  4. when the pipeline is being stopped by Ctrl+C orStopProcessing()

Caution

Adding the clean block is a breaking change. Because clean is parsed as akeyword, it prevents users from directly calling a command named clean asthe first statement in a script block. However, it's not likely to be aproblem. The command can still be invoked using the call operator(& clean).

Filters

A filter is a type of function that runs on each object in the pipeline. Afilter resembles a function with all its statements in a process block.

The syntax of a filter is as follows:

filter [<scope:>]<name> {<statement list>}

The following filter takes log entries from the pipeline and then displayseither the whole entry or only the message portion of the entry:

filter Get-ErrorLog ([switch]$Message){ if ($Message) { Out-Host -InputObject $_.Message } else { $_ }}

It can be used as follows:

Get-WinEvent -LogName System -MaxEvents 100 | Get-ErrorLog -Message

Function Scope

A function exists in the scope in which it's created.

If a function is part of a script, the function is available to statementswithin that script. By default, a function in a script isn't available outsideof that script.

You can specify the scope of a function. For example, the function is added tothe global scope in the following example:

function global:Get-DependentSvs { Get-Service | Where-Object {$_.DependentServices}}

When a function is in the global scope, you can use the function in scripts,in functions, and at the command line.

Functions create a new scope. The items created in a function, such asvariables, exist only in the function scope.

For more information, see about_Scopes.

Finding and Managing Functions Using the Function: Drive

All the functions and filters in PowerShell are automatically stored in theFunction: drive. This drive is exposed by the PowerShell Functionprovider.

When referring to the Function: drive, type a colon after Function, justas you would do when referencing the C or D drive of a computer.

The following command displays all the functions in the current session ofPowerShell:

Get-ChildItem function:

The commands in the function are stored as a script block in the definitionproperty of the function. For example, to display the commands in the Helpfunction that comes with PowerShell, type:

(Get-ChildItem function:help).Definition

You can also use the following syntax.

$function:help

For more information about the Function: drive, see the help topic for theFunction provider. Type Get-Help Function.

Reusing Functions in New Sessions

When you type a function at the PowerShell command prompt, the function becomespart of the current session. The function is available until the session ends.

To use your function in all PowerShell sessions, add the function to yourPowerShell profile. For more information about profiles, seeabout_Profiles.

You can also save your function in a PowerShell script file. Type your functionin a text file, and then save the file with the .ps1 filename extension.

Writing Help for Functions

The Get-Help cmdlet gets help for functions, as well as for cmdlets,providers, and scripts. To get help for a function, type Get-Help followed bythe function name.

For example, to get help for the Get-MyDisks function, type:

Get-Help Get-MyDisks

You can write help for a function using either of the two following methods:

  • Comment-Based Help for Functions

    Create a help topic using special keywords in the comments. To createcomment-based help for a function, the comments must be placed at thebeginning or end of the function body or on the lines preceding the functionkeyword. For more information about comment-based help, seeabout_Comment_Based_Help.

  • XML-Based Help for Functions

    Create an XML-based help topic, such as the type that's typically created forcmdlets. XML-based help is required if you are localizing help topics intomultiple languages.

    To associate the function with the XML-based help topic, use the.EXTERNALHELP comment-based help keyword. Without this keyword, Get-Helpcan't find the function help topic and calls to Get-Help for the functionreturn only autogenerated help.

    For more information about the .EXTERNALHELP keyword, seeabout_Comment_Based_Help. For more information about XML-based help,see How to Write Cmdlet Help.

See also

  • about_Automatic_Variables
  • about_Comment_Based_Help
  • about_Function_Provider
  • about_Functions_Advanced
  • about_Functions_Advanced_Methods
  • about_Functions_Advanced_Parameters
  • about_Functions_CmdletBindingAttribute
  • about_Functions_OutputTypeAttribute
  • about_Parameters
  • about_Profiles
  • about_Scopes
  • about_Script_Blocks
about_Functions - PowerShell (2024)
Top Articles
Paper Wasps, Yellowjackets and Other Stinging Wasps - Oklahoma State University
Capturing Employee Personal Trades
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Best Big Jumpshot 2K23
Craigslist Niles Ohio
Le Blanc Los Cabos - Los Cabos – Le Blanc Spa Resort Adults-Only All Inclusive
Body Rubs Austin Texas
Hk Jockey Club Result
Best Theia Builds (Talent | Skill Order | Pairing + Pets) In Call of Dragons - AllClash
Osrs But Damage
Aries Auhsd
South Ms Farm Trader
Goldsboro Daily News Obituaries
Jasmine Put A Ring On It Age
4156303136
Jc Post News
I Touch and Day Spa II
5 high school volleyball stars of the week: Sept. 17 edition
iLuv Aud Click: Tragbarer Wi-Fi-Lautsprecher für Amazons Alexa - Portable Echo Alternative
State HOF Adds 25 More Players
Justified Official Series Trailer
Les Rainwater Auto Sales
Craigslist Free Stuff Santa Cruz
Gem City Surgeons Miami Valley South
Saatva Memory Foam Hybrid mattress review 2024
Hennens Chattanooga Dress Code
Google Doodle Baseball 76
Lowes Undermount Kitchen Sinks
Providence Medical Group-West Hills Primary Care
Company History - Horizon NJ Health
Knock At The Cabin Showtimes Near Alamo Drafthouse Raleigh
Wics News Springfield Il
The best brunch spots in Berlin
Target Minute Clinic Hours
Account Now Login In
Doctors of Optometry - Westchester Mall | Trusted Eye Doctors in White Plains, NY
Xxn Abbreviation List 2023
Ts Modesto
49S Results Coral
P3P Orthrus With Dodge Slash
Royal Caribbean Luggage Tags Pending
Roto-Rooter Plumbing and Drain Service hiring General Manager in Cincinnati Metropolitan Area | LinkedIn
Joe's Truck Accessories Summerville South Carolina
Rochester Ny Missed Connections
Dollar Tree's 1,000 store closure tells the perils of poor acquisitions
Koninklijk Theater Tuschinski
Lacy Soto Mechanic
Former Employees
St Vrain Schoology
Richard Mccroskey Crime Scene Photos
Bama Rush Is Back! Here Are the 15 Most Outrageous Sorority Houses on the Row
Maurices Thanks Crossword Clue
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6640

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.