
Introduction to PowerShell Functions


In this article, I will take you through the process of mastering PowerShell functions step-by-step. We will start with the basics and gradually move on to more advanced topics, such as function parameters, return values, default values, and best practices. Let’s get started!
In my last article, I introduced the Practical PowerShell series. When working on PowerShell scripts, there might come a point where a set of instructions repeats code elsewhere in the script. It is also possible that you might want to incorporate code from elsewhere into your script so that you can easily call the code.
This description might remind you about cmdlets, which have names and, optionally, one or more parameters to control their operation. But what if you want the same thing for your code, like some code with a high reusability factor? Welcome to the world of PowerShell functions. Before we get too deep, let’s define exactly what we are talking about.
Therefore, definitions created by the caller in-session – such as functions and class definitions – are not visible to background jobs.
While you can reduce the duplication in the case of functions by referencing their bodies via the $using:scope – see this answer and the last snippet of sample code below – there is no analog for classes.
First, a simplified, self-contained example that shows the class redefinition only:
The above outputs The class name is: Test, as intended, which implies that the class was successfully (re)defined in the context of the job.
Finally, a self-contained example that shows the both class and function redefinitions:
The above outputs Return value from class method: computer1, as intended, which implies that both the class and the function were successfully (re)defined in the context of the job.
Writing a function
This function is named “HW,” its body – a line “Hello World!.”. Now, call this function from the command line: Call HW function
Result: Hello World!

Let’s call this function with declaring “People” argument: Call HW function
Result: Hello People!

Result: At line:1 char:14 + hw (“lovely” “people”)

It seems that everything is clear. Now, let’s look at the function I wrote to solve my task. I divided it into several parts to comment on each stage of the process. The full listing will be submitted below. The start of the function named Get-ADPCInfo The listing of Get-ADPCInfo 1.1. function
I gave this function the name Get-ADPCInfo Description of the function parameters for additional information. The listing of Get-ADPCInfo 1.2. function
Body of function
Clear the workplace and define what the script does if there is an error. The listing of Get-ADPCInfo 1.4. – error processing
#Clear the workspace
#What do functions do if there is an error
$ErrorActionPreference is an error processing cmdlet and defines how exactly PowerShell will take action if there is an error. For example, if I try to create an object that doesn’t exist, PowerShell will react with an error. Example: The example of an error
The $ErrorActionPreference parameter is set with the value to Continue by default, which means that you’ll get notified about an error, but the script (command) will try to continue anyway. In fact, you can set the $ErrorActionPreference to four variables: SilentlyContinue – continue despite the errors; Continue – doesn’t dismiss errors, if an error is not critical, send notification and continues; Stop – stop if there is any error; Inquire – prompts a request what should be done if there is an error. Importing Active Directory module and the information selection regarding the domain computers The listing of Get-ADPCInfo 1.5. function
# Loading the module AD so that it becomes available for use
#The number of days to designate computers working without interruption.
#Get the work–
The PowerShell function has access to those arguments it is running with, even if while defining this function, you didn’t set formal parameters. All the arguments the function was started with are automatically stored in the $(name) variable. In other words, there is an array of function parameters set upon function start stored in the $(name) variable. In PowerShell, like in most of the programming languages, you can set the list of formal parameters in the function description, which values will be replaced with the values of actual arguments while executing the function. The listing of formal parameters should be set in braces after the function name. Let’s define, for example, the function Sum, to establish the sum of two arguments: The example of working with arguments
While calling the Subtract function, its formal parameters will be replaced with actual arguments, defined either according to its position in the command line or by its name. The example of the Sum function:
When you are listing the arguments, you can use the names of formal parameters (order is not important). The example of the Sum function: rearrangement of arguments
Information’s output about the function of working. The listing of Get-ADPCInfo function 1.6. function’s output
” Overdue for Reboot””IP Address: “”IP Address: “
#Clear the workspace#What do functions do if there is an error#Loading the module AD so that it becomes available for use#The number of days to designate computers working without interruption.#Get the work–” Overdue for Reboot””IP Address: “”IP Address: “
Roughly speaking, each function can be divided into 3 parts. 1. Function description for help PowerShell «Get-Help». 2. The work of the function (defining variables, filters, arrays);

3. Function result’s output.
Saving the Script!

After that, this function will be available to you every time you run PowerShell.

Importing module on another computer
new-item -type directory -path $homeDocumentsWindowsPowerShellModules
While importing the module, you can receive the notification from the PowerShell Security Policy. To solve this problem, you can set the PowerShell Execution Policy, which will allow executing scripts from the other sources (even the script created on the machine from the same network won’t work). Set the Execution Policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

Scripts
A script is a text file with a .ps1 extension containing PowerShell code. The code consists of cmdlets and (optionally) functions. You can call scripts in various ways:
The ability to run PowerShell scripts depends on the local machine’s current execution policy. This is a security measure to prevent malicious scripts from running. Scripts from Microsoft are generally signed, but many community-sourced scripts downloaded from the internet are usually not. You may need to run Set-ExecutionPolicy unrestricted before you can run scripts created by others, provided company policies do not prevent you from modifying the execution policy.
Make PowerShell Work for You
It is ambitious to discuss functions and parameters in PowerShell in one article. I have not touched on other subjects, such as command sets and dynamic parameters. These might be topics for another article.
I hope that I have encouraged you to write reusable code, not only to leverage scripts and functions but also to correctly define code. Make PowerShell work for you when possible, letting it handle parameter validation and checking other constraints such as types. This enables you to focus on the task while making code less complex and improving readability.
If you have questions or comments, feel free to reach out in the comments. If not, wait until the next article, where I will discuss flow control.
PowerShell function naming conventions
When calling a function in PowerShell, you may encounter some common errors. Here are some of the most common errors and how to troubleshoot them:
Remember, PowerShell is case-insensitive, but it’s always a good practice to keep the case consistent for readability and to avoid confusion.
Different ways to Call a function with parameters in PowerShell
PowerShell supports several ways to pass parameters to a function. Here are some examples:
Positional Parameters
This method works based on the position of the parameters in the function definition. It’s straightforward for functions with one or two parameters but can be confusing for functions with multiple parameters. Here is another example with multiple parameters:
This script defines a function “Greet-Person” that takes two parameters, “FirstName” and “LastName”. The “Position” attribute is used to specify the position of the parameters when the function is called without parameter names.
In the function call “Greet-Person “John” “Doe”, the script passes “John” as the “FirstName” and “Doe” as the “LastName” based on their positions. The function will output “Hello, John Doe”.
Named Parameters
Named parameters allow you to specify the parameter name when calling the function, making it clear which value corresponds to which parameter.
This method is particularly useful when a function has many parameters, or when you want to skip some optional parameters. As far multiple parameters, here is an example script:
Passing an Array to Function
If a function accepts multiple parameters, you can pass them as an array. This is helpful when you have a list of values to pass to the function.
This will output: 1+2+3.
Piping Input to Functions
Functions in PowerShell are similar to functions in other programming languages. They take input, process it, and return output. You can pass parameters to a function, and it can return a value. You can use functions to extend the functionality of existing cmdlets.
Nested function calls
Functions can call other functions internally as well. Let’s do the Sum of Squares Calculation with nested functions.
This allows composing complex logic across multiple nested function calls. As seen above, calling functions by passing parameters allows added flexibility. For advanced details, See PowerShell Function Parameters
Tips on best practices for calling a function in PowerShell
Let’s start from the beginning. I won’t take up much of your time explaining how to install and update PowerShell on Windows 8.1 or earlier versions because these operating systems are likely to be found only in a museum, if at all. Instead, let’s focus on the more relevant Windows 11 and Windows Server 2022, which are currently the two most popular versions of the Windows OS. Naturally, the latest version of PowerShell is included by default in both.
And yes, before working with PowerShell, it is highly recommended to update it. The simplest way to do so is by downloading the required version from the official site. First, install Net Framework 4.5 because it’s necessary for the installation of the WMF 5.0 (Windows Management Framework 5.0). Further, naturally, proceed with installing the required WMF. You can use this tab to pick an installer needed for your PowerShell.
*Windows 10 isn’t updating automatically via Windows Update, and it has PowerShell 5.0 installed by default. With automatic updates enabled, PowerShell updates from 5.0 to 5.1. (details are here).


To import AD modules into PowerShell, use this command:
Now we have PowerShell all suited up to work with AD.
PowerShell Mandatory Parameter
In this example, the Get-FileContent function has a mandatory path parameter. If the caller does not specify a value for the path parameter, PowerShell prompts them to enter a value.
Wrapping up
What is a PowerShell function?
What is the difference between function and method in PowerShell?
How to call a PowerShell function with parameters?
To call a PowerShell function with parameters, you can simply provide the values for the parameters when calling the function. For example, if you have a function called “MyFunction” with parameters “Param1” and “Param2”, you can call it like this: “MyFunction -Param1 Value1 -Param2 Value2”.
How to call a PowerShell function from ps1 file?
How do I permanently add a function in PowerShell?
To permanently add a function in PowerShell, you can create a PowerShell script file (.ps1) and define your function within it. Then, you can save the script file in a directory that is included in your system’s PATH environment variable. This way, the function will be accessible from any PowerShell session.
How do you call a function inside a function in PowerShell?
How to exit a PowerShell function?
Can a PowerShell function return multiple values?
What is the difference between a function and a cmdlet in PowerShell?
Table of contents
For example, if we want to use the “Compress-7Zip” function from the “7Zip4PowerShell” module, we would write:
#Import 7zip PowerShell Module
Import-Module 7Zip4PowerShell
#Call a function to zip a File
Compress-7Zip “C:Temp” -ArchiveFileName backup.zip -Format Zip
How to Generate a Function Quickly with Parameters and Comment Documentation?
You can leverage the snippets feature in Microsoft PowerShell ISE to quickly generate a function for PowerShell! This feature allows you to insert predefined scripts into your current script. To use a snippet, go to the Edit menu, then Start Snippets, and you’ll see a list of snippets. For functions, choose Cmdlets (Advanced Function).
This snippet will create a function with parameters and basic comment-based help. You just need to replace the placeholders with your specific content.
PowerShell Return Value from Function
You can use the return statement to specify the value that a PowerShell function returns. You can use it to return any data type, including strings, integers, arrays, and objects. The return statement terminates the function and returns the specified value to the caller.
In this example, the Get-Message function returns the string “Hello, World!” when it is called. To use the output of a function, you assign it to a variable:
How to Call a Function from another PowerShell script file?
# Dot source the script
. C:TempMyFunctions.ps1
# Now you can call the function from PS1 file
Get-RectangleArea -length 10 -width 5
Similarly, you can call functions from PowerShell modules, too. More here: How to call a function from an External file in PowerShell?
In this function, $Name is a parameter. When calling this function, you can pass a name to it, and it will return a greeting with that name.
This will output: Hello, John.
Understanding PowerShell Function Parameters
Function parameters are variables that are passed to the function when it is called. They enable you to pass data to the function and make it more flexible. PowerShell supports two types of function parameters: named parameters and positional parameters.
Creating a PowerShell Function with Parameters
Parameters allow you to pass input values to your PowerShell functions. They enable you to customize the behavior of your functions based on the values provided. Let’s create a simple PowerShell function that takes two parameters and returns their sum.
This function takes an optional count parameter and retrieves the top count processes running on the computer. It then converts each process to an object with three properties (Name, CPU, and Memory) and returns an array of these objects.
Handling multiple parameters in PowerShell functions
PowerShell functions can have multiple parameters, allowing you to customize the behavior of the function in various ways. When defining multiple parameters, you can specify their type and default values, if any. When calling a function with multiple parameters, you need to provide the values in the same order as they are defined in the function. Alternatively, you can specify the parameter values by parameter name, which allows you to provide them in any order.
Examples of PowerShell functions with multiple parameters
Here are some examples of PowerShell functions with multiple parameters:
Parameter validation in PowerShell Functions
Validate script attribute:
Similarly, the Validate Range and Validate Set can be used as:
Best Practices for Using PowerShell Functions
Here are some best practices for using PowerShell functions:
Benefits of using PowerShell functions
Here are some of the benefits of using PowerShell functions:
Script Parameters
Calling a function in PowerShell means executing the code inside the function. When you call a function, you pass it any necessary parameters, and it returns the output. The easiest way to call a function in PowerShell is using its name. When you call a function, PowerShell looks for the function in memory. If the function is not already loaded into memory, PowerShell will load it from the script file.
Let’s take a step-by-step look at how to call a function in PowerShell.
Simple Function Calls
Output: The current time is: 12/12/2021 18:03:07
Reusable Code
If you create a function that redefines an existing command, the existing definition is overwritten in the current session. The code’s output will be returned to the caller, and you can output the result to the screen or assign it to a variable for further processing.
In addition to the function itself, you can also define parameters for the code contained in the function. The code within the function can then perform its task using information passed through the parameters, as the parameters become variables usable in the context of the function’s code.
This code is acceptable when drafting a script or working on a proof of concept. However, issues might become apparent when using the function later or somebody else who is less familiar with the use case takes responsibility for the code.
Among the issues with this function are:
Can you guess what happens if you do not pass the ID parameter or when the ID is empty? All mailboxes are returned and Set-Mailbox will happily hide all the mailboxes from address lists. It is probably not something you intended.
Get-DistributionGroupInfo -Identity ‘DG-X’
Additional unnamed parameters can be specified as Position=1, etc.
Get-Help Get-DistributionGroupInfo -Full
I do not know anyone who uses !?, but you can if you want.
I recommend using strict typing with parameters whenever possible. Typing helps with troubleshooting usage and also helps to document the code, as explained later. One thing to consider is that values might get converted through interpretation. For example, if you pass a parameter value 123, and a string is expected, PowerShell will happily convert this to a string representation, ‘123’.
When we put the code for this function in a script file, for example, MyDemo.ps1, it becomes available within our PowerShell session. To accomplish this, we need to dot source it to define it in our session. We can then call it – provided the Exchange Online Management Shell is loaded and connected – and inspect its definition by calling Get-Help, which also includes documentation.
Formulating the Task
Occasionally, I face the necessity to get a list of computers from AD (Active Directory) with a short description of each machine, including computer name, IP address, and uptime. Naturally, you can just go to the Active Directory server and find all you need to know, but what if there was a much easier way? It seems unnecessarily redundant to go through all that when you can achieve the same result with one PowerShell command. With a simple Get-ADpcinfo command, you can find this list instantly and display it. How to do that and what problems you may have I can tell from my own experience.
Syntax and structure of a PowerShell function
Once you have defined the function, you can implement its functionality by adding the necessary code inside the curly braces. This code will be executed whenever the function is called.
Call a function in PowerShell
When we run this code, the function executes and outputs the message “Hello, World!” to the PowerShell console. If your function has parameters, you need to provide the values for those parameters when calling the function.
PowerShell Parameters Default Value
PowerShell function parameters can have default values, which are used when the caller does not specify the parameter. Default values make parameters optional and enable you to create more flexible functions. To define a default parameter value in PowerShell, you can assign a value to the parameter when you declare it.
In this example, we define a function called Get-ServiceStatus that checks the status of a given service. The function takes a $ServiceName parameter and uses it to retrieve the service status using the Get-Service cmdlet. We call the Get-ServiceStatus function and pass the value “Spooler” to the $ServiceName parameter. If the service is running, it returns the message “Service is running”. Otherwise, it returns “Service is not running”.
Conclusion
Functions, with their ability to encapsulate logic and promote reusability, are powerful tools in the hands of any PowerShell scripter. Calling functions is fundamental to leveraging PowerShell’s modular capabilities. This beginner’s guide has aimed to break down the process of defining, calling, and manipulating functions in PowerShell into comprehensible chunks. We covered key concepts like defining reusable logic in functions, calling them by name or variable, using parameters, pipelines, and more. Through detailed examples ranging from basic to advanced, you now have practical exposure to applying these techniques.
Whether you’re working interactively or with scripts, knowing function invocation best practices will enable better coding. In this guide, we covered everything you need to know about calling a function in PowerShell. We started with the basics, including what a function is and how to call it. We then covered best practices, common errors, and advanced techniques. Finally, we provided examples and a cheat sheet for calling a function in PowerShell.
How do I use a function from another file in PowerShell?
To use a function from another file in PowerShell, you can use the “dot sourcing” technique. This involves prefixing the file name with a period (dot) and a space. Here’s an example: . .PathToYourScript.ps1 . After you’ve dot sourced the script, you can call the function defined in that script just like any other function in your current session.
How do I call an executable in PowerShell?
To call an executable in PowerShell, you can simply specify the path to the executable file and provide any necessary arguments. Here is an example:& “C:PathToYourExecutable.exe” -Argument1 -Argument2In this example, replace “C:PathToYourExecutable.exe” with the path to your executable file, and “-Argument1 -Argument2” with any arguments that your executable requires. The “&” operator is known as the call operator, and it’s used to execute a command or script that is stored in a string or a variable.
How do I import a module into a PowerShell script?
How to call a function in PowerShell with parameters?
What is the function call operator in PowerShell?
Begin, Process, End
An example is when you want to count how many objects you have processed, as the number of objects passed through a pipeline is unknown upfront. Another example of this would be the Sort-Object command, which can only sort objects when all objects have been passed to it.
In this article, I tried to write one of the simplest functions and show you a part of the possibilities that PowerShell can offer! It’s neither perfect nor wholly self-sufficient but it’s working. And it’s useful. I hope that my advice and solution will help you!
This material has been prepared in collaboration with Vladyslav Savchenko Pre-sales Engineer at StarWind, and Viktor Kushnir, Technical Writer with almost 4 years of experience at StarWind.



