PowerShell Function: Syntax, Parameters, Examples

-

|

Introduction

There are two types of PowerShell Functions, basic and advanced. A basic PowerShell Function is a list of PowerShell statements with an assigned name.

On the other hand, an advanced PowerShell function acts like cmdlets. A PowerShell function defines parameters, comment-based help information and statement blocks.

This guide provides a step by step guide on how to write a PowerShell function. At the end of the guide you should be able to write your own PowerShell function.

Powershell Function Syntax

The syntax of a PowerShell Function is

1 Function  <name> {
2 <#
3 .SYNOPSIS
4 .DESCRIPTION
5 .PARAMETER
6 .EXAMPLE
7 #>
8 Param (
9 [type]$parameter1 [,[type]$parameter2]
10 )
11 Begin {
12 <Begin statement list>
13 }
14 Process {
15 <Process statement list>
16 }
17 End {
18 <End statement list>
19 }
20 }

Powershell Function Syntax Explained

This section explains the meaning of each value in the syntax. To make it easy to explain, I have added line numbers (1 to 20) to the syntax.

Line numberSyntax Value (s)Meaning
1Function <name> {A PowerShell function begins with the word Function followed by the <name> of the function. Then an opening bracket, { – opens the function block
2<#Represents the opening block of the comment-based help
3.SYNOPSISProvides a short description of the PowerShell function
4.DESCRIPTIONUsed to provide a detailed long description of the function
5.PARAMETERDescribes each parameter defined in the param block,what they do and how to use them
6.EXAMPLEUsed to add examples of how to use the function
7#>Represents the closing block of the help information
8Param (To define parameters you start with the word param and open the block with (
9[type]$parameter1 [,[type]$parameter2]These are the parameters of the function. [type] defines the type of the parameter. Then the name of the parameter. The parameters are separated by a comma (,).
10 )Closes the param block
11Begin {Opens the Begin block of the function
12<Begin statement list>The list of Powershell statements within the Begin block.
13 }Closes the Begin block
14Process {Opens the Process block of the function.
15<Process statement list>The list of Powershell statements within the Process block.
16 }Closes the Process block
17 End {Opens the End block of the function.
18<End statement list>Powershell statements within the End block
19 }Closes the End block
20 }Closes the function block

Powershell Function Example

In this section, I will use an example to explain the syntax in the last section.

You will learn (step by step) how to define the function block, add parameters and help files. This section will end with a brief explanation of the Begin, Process and End blocks.

The steps in this example will help you write a PowerShell function from ground up.

Powershell Function Example (Defining a PowerShell Function Block)

This section covers the first stage in writing a Powershell Function: defining the function block.

To follow the demo in this guide you need PowerShell ISE. ISE is pre-installed in Windows 10. To open it, type ISE into the Windows 10 search bar

Follow the steps below to define the function block.

  • Open PowerShell ISE. Then enter the word Function followed by Export-ADUsers. Next, a bracket opening the function block. When you finish you should have something like this.
Powershell Function Example (Defining a PowerShell Function Block)
In this example, Export-ADUsers is the name of the function.
  • Next, place your mouse after the opening bracket, {. Then press Enter key 5 times and type a closing bracket, } to close the function block. Your function should now look like the image below.
At this point, you have set up the PowerShell function block. Next step is to define the parameters by adding a param block.

Powershell Param (How to Add Parameters to a PowerShell Function)

  • To add a param block, enter the word param followed by ( )

The next step is to define your first parameter, within the param block.

  • Enter [, followed by the word parameter. Then enter an opening bracket, ( followed by Mandatory=$true or $false. Then another comma followed by position=0 followed by a comma. Next, enter ParameterSetName=’SearchLoc’. Finally, add a closing ) and then ]. Here is what your function should now look like.
Powershell Param (How to Add Parameters to a PowerShell Function)
Here is what the last line of code does: it says that the parameter you will add below this line is required. That is, when a user runs this PowerShell function, the parameter must be called. It then says the position of the parameter is zero, 0. Finally, it adds a parameter set.
A PowerShell function can have multiple parameter sets. Parameters in the same parameter set can be in the same command line. If you try to call two parameters from different parameter sets in one command line, you will receive an error message. More on this later.
  • To add your first parameter, place your cursor behind the closing ] and press Enter.
  • Next, type [, followed by the word string. Then enter these blocks []] followed by a $ sign then the name of the parameter. Finally, add a comma. Here is the updated function.
Powershell Param (How to Add Parameters to a PowerShell Function)
You have just added a string parameter type. Another parameter type is switch. While a string parameter requires an input, a switch parameter does not.
  • To add a second string parameter in the same parameter set, enter the following into your code.
[parameter (Mandatory=$true, position=1, ParameterSetName='SearchLoc')]
[string]$Server

Here is your updated PowerShell Function.

The last defined parameter is a string parameter in position 2 and in SearchLoc paremeter set. If this is your last parameter, DO NOT add a comma after it. But if you need to add another parameter, add a comma then include your next parameter. After defining parameters, the next logical thing is to add a help information to your function.

In the updated function below, I have added two more parameters.

Before you proceed, save the function as Export-ADUsers: File -> Save As

How to Add Help to a PowerShell Function

Follow the steps below to add help to the PowerShell Function

  • Place your cursor after the opening block of the function, {. Then press Enter key multiple times to add some spaces.
  • Beneath the opening block, paste the following codes
<#
.SYNOPSIS

.DESCRIPTION

.PARAMETER

.EXAMPLE
#>

At this stage, your function should look something like this

  • Next, add contents to the short (SYNOPSIS) and long DESCRIPTION sections. Here is what the function should now look like.
add contents to the short (SYNOPSIS) and long DESCRIPTION sections of the powershell function
  • Then add information about each parameter. The syntax is .PARAMETER, then the parameter name. See the image below for the updated PowerShell function.
help added for each parameter
  • Finally, for the help block, add an Example. Here is the updated PowerShell function

How to Add Statements to the Begin, Process and End Blocks

Now that you have added parameters and help to the Powershell function, it is time to add the actual scripts to the function.

Before I begin, I will like to revisit the syntax of a Powershell function. A summarized version is shown below:

Function <name> {
<#

#>
param (

)

Begin {

}
Process {

}

End {

}

}

So far, we have added parameters and help information into the function. In this section I will discuss how to add statements to the 3 blocks of a PowerShell Function.

The Begin block is usually where you add scripts you require in the Process block. In Export-ADUsers function, I used the Begin block to extract the credential entered in the Credential parameter.

To export users from Active Directory, you need the right permission. The Credential parameter is used to specify a user name with permission to access Active Directory.

To work with the credential, I will use the Get-Credential cmdlet to extract the credential. But because this parameter is optional, I will add an IF statement as shown below.

Begin {
If ($Credential) {
$Cred = Get-Credential $Credential
}

}

This command will only run if the Credential parameter is called in the Export-ADUsers command line.

The Process block is where you add the main scripts for the function. In this instance, this block contains the Get-ADUser cmdlet.

The End block can be used for final scripts. In this example, I left it blank.

Giving the details of the scripts in this PowerShell function is beyond the scope of this guide. To download the completed function click download Export-ADUsers function.

Conclusion

Writing a PowerShell function may appear complex but it is actually easy. I hope this guide simplified it for you.

If you have any question or comment, use the “Leave a Reply” form at the end of this page. You could also share your PowerShell scripting experience with other readers.

Other Helpful Guides

Additional Resources and References

  • Was this post Helpful?
  • YesNo

LEAVE A REPLY

Please enter your comment!
Please enter your name here

ADVERTISEMENTS

FEATURED POSTS

Best Christian Movies on Netflix

The 10 Best Christian Movies on Netflix

This Itechguide reviews the 10 best christian movies on Netflix. The movies are listed in reverse order – with the 10th movie...
How to Change Orientation in Google Docs

How to Change Orientation in Google Docs

This Itechguide teaches you how to change orientation in Google Docs. The guide covers steps to change orientation in Google Docs from...
How to Delete Google Photos

How to Delete Google Photos

This Itechguide teaches you how to delete Google Photos. The guide offers steps to delete Google Photos from the Google Photos App...
How to Install Windows 10 1909 Update Manually

How to Install Windows 10 1909 Update Manually

This Itechguide teaches you how to install Windows 10 1909 update manually. Windows 10 1909 (otherwise known as Windows 10 November update)...
How to Create a Poll on Facebook

How to Create a Poll on Facebook

This Itechguide teaches you how to create a poll on Facebook. You can create a poll on Facebook from a Facebook page...

AMAZON DEALS

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

ADVERTISEMENTS

BEST OF ITECHGUIDES

How to Change Birthday on Facebook

How to Change Birthday on Facebook (from the App or PC)

This Itechguide teaches you how to change birthday on Facebook. The guide contains steps to change birthday on Facebook from the Facebook...
How to Lock a Row in Google Sheets

How to Lock a Row in Google Sheets

This Itechguide teaches you how to lock a row in Google Sheets. As at the time of writing...
How to Download and Install Windows ADK for Windows 10

How to Download and Install Windows ADK for Windows 10

Introduction The steps in this guide demos how to download and install Windows ADK for windows 10.
How to do Subscript in Google Docs

How to do Subscript in Google Docs

This Itechguide teaches you how to do subscript in Google Docs. The guide offers steps to do subscript in Google Docs from...
powershell sleep

PowerShell Start-Sleep Command: Syntax, Examples

Introduction Powershell Sleep (Start-Sleep) Cmdlet is a very useful scripting tool. There may be instances when you want to...

RECENT POSTS

How to Change Facebook Page Name

How to Change Facebook Page Name

This Itechguide teaches you how to change Facebook page name. The guide covers steps to change Facebook page name from a PC...
How to Change YouTube Channel Name

How to Change YouTube Channel Name

This Itechguide teaches you how to change YouTube channel name. The guide covers steps to change YouTube channel name from a PC.
How to Bold Text on Facebook Post

How to Bold Text on Facebook Post

This Itechguide teaches you how to bold text on Facebook post. The guide covers steps to bold text on Facebook post from...
Best Crime Documentaries on Netflix

The 10 Best Crime Documentaries on Netflix

This Itechguide reviews the 10 best crime documentaries on Netflix. The documentaries are listed in reverse order – with the 10th documentary...
Best Netflix Series

The 10 Best Netflix Series

This Itechguide reviews the 10 best Netflix series. The series are listed in reverse order – with the 10th series on top....

AMAZON DEALS

MUST READ

How to Post on Facebook

How to Post on Facebook (from a PC or Smartphone)

Introduction Posting on Facebook is easier than you can imagine! This guide walks you through how to post on...
Best Thrillers on Netflix

The 10 Best Thrillers on Netflix

The thrillers on Netflix is quite a large number of movies. Knowing the best thrillers to watch can be a challenge.
powershell replace

PowerShell Replace “Method” and “Operator”: Syntax, Examples

Introduction PowerShell Replace can be used to replace character strings, texts or special characters. PowerShell has a Replace...
How to Add Administrator to Facebook Page

How to Add Administrator to Facebook Page

Introduction After creating a Facebook page you can assign page roles. There are different page roles you can assign...
disable cortana windows 10 featured

How to Disable Cortana in Windows 10 (2 Methods)

Introduction Some Windows 10 users may not like Cortana. Solution? Disable Cortana. You are probably reading this because you...

AMAZON DEALS

By using this website you agree to accept our Privacy Policy and Terms & Conditions