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.

Advertisement

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)
Advertisement
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.
Advertisement

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

network discovery keeps turning off server 2016

How to Fix Network Discovery If it Keeps Turning Off in Server 2016

Does network discovery keep turning off in your Windows server 2016? It is likely that one of its dependent services is not...
how to install windows 10 1903 update manually

How to Install Windows 10 1903 Update Manually

Windows 10 1903 Update was released in May, 2019. But some users are not yet offered the update via automatic update. The...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...

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...

BEST OF ITECHGUIDES

iPad Won't Charge

iPad Won’t Charge? How to Fix It

Why Won't iPad Charge? If your iPad won't charge it could be for a number of reasons. Here are...
how to change wifi password

How to Change Wifi Password for Any Wifi Router

Introduction To change your Wifi password (PIN), you need the IP address and admin login for the router. Once...
How to Convert Text to Number in Excel

How to Convert Text to Number in Excel in 4 Easy Ways

Introduction There are 4 ways you can convert text to number in Excel. This guide demonstrates the 4 ways...
windows safe mode

2 Easy Ways to Start Windows 10 Safe Mode

Introduction In previous versions of Windows you could start safe mode by pressing F8. But in Windows 10, F8...
dns server not responding featured image

“DNS Server Not Responding” Error [Fixed]

What Could Cause "DNS Server Not Responding" Error Message? The error messages "DNS Server Not Responding" or "DNS...

RECENT POSTS

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...
bootrec /fixboot access is denied

How to Fix BootRec /FixBoot Access is Denied Error in Windows 10

Introduction BootRec /FixBoot Access is Denied Error in Windows 10? This error is likely caused by corrupt EFI directory.
Reset Windows 10

How to Reset Windows 10 (2 Methods)

Introduction If your Windows 10 is broken, one available way to fix it is to use Windows 10 reset....
system restore windows 10

How to Enable and Use System Restore in Windows 10

Introduction System restore in windows 10 is a very important tool that is probably ignored by most users. But...
windows has stopped this device code 43

How to Fix Windows Has Stopped this Device Code 43 Error

Introduction Sometimes you may receive "Windows has stopped this device code 43" error. This error is likely to come...
Windows could not automatically detect this network's proxy settings

How to Fix “Windows Could not Automatically Detect this Network’s Proxy Settings”

Introduction You suddenly lose the ability to connect to the internet. Then you run network troubleshooter and it returns...
printer offline

5 Ways to Restore Your Printer Online If Status is Offline

Introduction Is your printer offline? Setting it online is very simple but sometimes it is more than just setting...

How to Fix “BootMgr is Missing” Error in Windows 10

Introduction If you receive Fix "BootMgr is missing" Error in Windows 10, the default response is panic! But you...
windows 10 search featured

How to Fix Windows 10 Search If it Stops Working

Introduction Are you having troubles with Windows 10 search? Apparently, it is a fairly common problem with a number...
oooops, something went wrong. reload

How to Fix “Oooops something went wrong. reload” Spotify Error

Introduction If you receive "Oooops something went wrong. reload" Spotify error, do not panic. The fix is simpler than...

MUST READ

ForEach-Powershell

PowerShell ForEach: Syntax, Parameters, Examples

What is PowerShell ForEach? PowerShell ForEach (ForEach PowerShell) is a PowerShell construct used in iterating through values in a...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...
powershell delete folder or File

How to Delete Folders or Files in PowerShell

Introduction You can delete folders and files in PowerShell using the Delete method or Remove-Item Cmdlet. This guide shows...
Check Disk (CHKDSK) Windows 10

Check Disk (CHKDSK) in Windows 10: Syntax, Parameters, Examples

Introduction Check Disk (CHKDSK) is a Windows 10 command tool that checks a disk for errors, fixes errors, recovers...
schedule shutdown windows 10

How to Schedule Windows 10 to Shutdown at Specified Time

Introduction If you want to schedule shutdown for windows 10 (turn off) at specified time, this guide is for...

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