Gice

Technology and General Blog

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.

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
 

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

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

It will show you the following output:

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

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.

 

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

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
       
   

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

ComputerName, Computer, ServerName, Host, and Machine:

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

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

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

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

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

> Get-Command -Name TestMrCmdletBinding -Syntax

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *