If you want to use PowerShell Scripts and commands in different scenarios, you can transform them into reusable functions. PowerShell has a lot of flexibility in terms of how you represent the code in a script.

If you pursue writing out hundreds of lines of codes in a single code block, then it is not the proper method because it is usually difficult to read a big block of code. You can break it down into small functions to make the program more understandable, organized, and reusable.

What is a Function in PowerShell?

In PowerShell, a function is a collection of code with optional input and output. It is the formation of a sequence of instructions to execute one or many times by simply invoking it rather than copying it repeatedly. Function improves the readability and usability of your code substantially, making it much easier to deal with repeated code.

It takes parameters as input and returns values assigned to some variables, piped to other functions, or cmdlets as input or displayed as an output on the screen. Rather than repeating the code, the function can be called as many times as needed after being defined in the script. In PowerShell, there are two types of functions: basic and advanced.

Basic Functions in PowerShell

The simplest form of a function that we can create in PowerShell is called a “basic” function. These functions do not utilize any of the built-in features. A set of curly braces { } is used to define the body of the function. When working with PowerShell functions, the easiest option for administrators is to use basic functions because these functions do not have any inherited features. You have to define all error streams in your function’s code explicitly.

Advanced Functions in PowerShell

Advanced functions have the same properties as basic functions, but they include additional features that basic functions do not have. For instance, PowerShell contains streams like Verbose, Warning, Debug, Error, etc. These streams are essential for showing output accurately.

Creating Basic Functions in PowerShell

Now, we will check out the method of creating basic functions in PowerShell. For this, open your Windows PowerShell ISE and create a new file.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-190.png" data-lazy- height="646" src="data:image/svg xml,” width=”787″>

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-192.png" data-lazy- height="574" src="data:image/svg xml,” width=”803″>

The function keyword is used to declare a function in PowerShell, followed by the function name and curly braces. The function’s code or body is within those curly braces { }.

function GetVersion {

$PSVersionTable.PSVersion


 }

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-194.png" data-lazy- height="215" src="data:image/svg xml,” width=”738″>

We will execute this “Get-Version” function at run time. Now, save the script as “testfile1.ps1” and run it.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-196.png" data-lazy- height="514" src="data:image/svg xml,” width=”910″>

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-197.png" data-lazy- height="218" src="data:image/svg xml,” width=”734″>

In the PowerShell terminal, call the created function by using its name.

It will show you the following output:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-198.png" data-lazy- height="249" src="data:image/svg xml,” width=”791″>

As the function gets loaded into your system memory, you can view functions on the Function PSDrive. For this, use the “Get-ChildItem” command to check the child items of the Function PSDrive. Here, the “-Path” option is utilized to specify the path of the function PSDrive.

> Get-ChildItem -Path Function:Get-*Version

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-199.png" data-lazy- height="224" src="data:image/svg xml,” width=”891″>

From the current session, you can remove the defined function by using the “Remove-Item” command. Execute the below-given command for this purpose.

> Get-ChildItem -Path Function:Get-*Version | Remove-Item

Use the pipe operator [“|“] so that the command will pipe out the child items of the Function PSDrive to the “Remove-Item” command. Then, the “Remove-Item” cmdlet will remove the created functions from the session.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-200.png" data-lazy- height="322" src="data:image/svg xml,” width=”914″>

To verify the removal of the function, invoke the “Get-Version” function. It will show you the following output:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-201.png" data-lazy- height="238" src="data:image/svg xml,” width=”926″>

Functions Parameter in PowerShell

Now, we will write a function that queries all of a system’s commands and returns the number of commands with certain parameter names. If you want to do so, execute the below-given script in your PowerShell:

function GetMrParameterCount {


    param (


        [string[]]$ParameterName


    )

    foreach ($Parameter in $ParameterName) {


        $Results = Get-Command ParameterName $Parameter ErrorActionSilentlyContinue

        [pscustomobject]@{


ParameterName = $Parameter


NumberOfCmdlets = $Results.Count


        }


    }

}

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-202.png" data-lazy- height="373" src="data:image/svg xml,” width=”923″>

Now, we invoked the “Get-MrParameterCount” with the parameters:

ComputerName, Computer, ServerName, Host, and Machine:

> GetMrParameterCount ParameterName ComputerName, Computer, ServerName, Host, Machine

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-203.png" data-lazy- height="271" src="data:image/svg xml,” width=”1081″>

Creating Advanced functions in PowerShell

It’s really easy to turn a basic PowerShell function into an advanced function. Advanced functions feature several common parameters that are automatically added to the function. Now, we will turn the basic function defined in the previous section into an advanced function:

function TestMrParameter {


    param (


        $ComputerName


    )


    Write-Output $ComputerName

}

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-204.png" data-lazy- height="270" src="data:image/svg xml,” width=”644″>

Notice that the “Test-MrParameter” function has no common parameter. The common parameters can be viewed in different ways. One method is to use “Get-Command” with the “-Syntax” option to look at the syntax:

> Get-Command -Name TestMrParameter -Syntax

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-205.png" data-lazy- height="227" src="data:image/svg xml,” width=”759″>

To make the function an advanced function, add “CmdletBinding”:

 function TestMrCmdletBinding {

    [CmdletBinding()] #<<– This turns a regular function into an advanced function


    param (


        $ComputerName


    )

    Write-Output $ComputerName

}

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-206.png" data-lazy- height="280" src="data:image/svg xml,” width=”890″>

Again, you can check the syntax and parameters of this advanced function by executing the below-given commands:

> Get-Command -Name TestMrCmdletBinding -Syntax

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-207.png" data-lazy- height="249" src="data:image/svg xml,” width=”886″>

> (Get-Command -Name TestMrCmdletBinding).Parameters.Keys

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/word-image-208.png" data-lazy- height="354" src="data:image/svg xml,” width=”895″>

Conclusion

You can divide code into separate building blocks by using functions in PowerShell. They not only assist you in breaking down your code into smaller and more manageable pieces, but they also push you to produce testable and readable code.

Functions also substantially improve your code’s readability and usability, making it much easier to deal with repeated code. This article shows you some methods for using functions in PowerShell, including basic and advanced ones.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/talha-150×150.jpg61132d46aefe7.jpg" height="112" src="data:image/svg xml,” width=”112″>

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.