Your Getting Started Guide to Powershell Functions

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

A new language is coming to the web, and it’s not JavaScript. Powershell functions are short scripts that can be used anywhere in your codebase for a variety of purposes. It will change how you write software forever

The “powershell functions with parameters” is a guide that will teach you how to create and use PowerShell functions. The article also provides examples of how to set up the function, what the function can do, and how to run the function.

Your Getting Started Guide to Powershell Functions

You should learn about code modularization after you’ve become used to developing PowerShell scripts. Modularization is basically a fancy way of saying “writing code in chunks.” PowerShell functions are one of the greatest methods to achieve this in the PowerShell universe.

When writing a PowerShell script, you have a lot of flexibility in terms of how you express the code. In a single, unbroken block of code, you might create a thousand lines of code that do hundreds of jobs. That would be a huge mistake. You should instead write functions.

Functions improve the usefulness and readability of your code substantially, making it much simpler to deal with. You’ll learn how to build functions, add and manage parameters for your functions, and set up functions to take pipeline input in this course. But first, let’s review some terms.

This article is based on my book PowerShell for Sysadmins: Workflow Automation Made Simple. If you liked what you learned in this video, you should check out the book to learn more about functions and other PowerShell features.

Cmdlets vs. Functions

The notion of a function may seem familiar to you since it resembles the cmdlets you’ve undoubtedly previously used. Start-Service and Write-Host, for example, are commands that are equivalent to functions. These are identified chunks of code that address a specific issue. The way each of these components is created is what distinguishes a function from a cmdlet.

PowerShell does not allow you to create a cmdlet. It’s written in a different programming language, usually C#. After that, the cmdlet is built and made accessible in PowerShell.

Functions, on the other hand, are written in PowerShell rather than a different programming language.

Using the Get-Command cmdlet and its CommandType option, you can see which commands are cmdlets and which are functions, as seen below.

Function Get-Command –CommandType

This command retrieves all of the functions presently loaded into your PowerShell session, as well as any functions included inside modules that are exposed to PowerShell.

Understanding and Creating PowerShell Modules is a related topic.

Prerequisites

If you want to follow along with all of the examples, make sure you have PowerShell installed. This lesson does not have any special version requirements. Also, make sure you have a good code editor, such as Visual Studio Code, where you can copy, paste, and execute code snippets.

Creating a Basic Function

You must first declare a function before you can utilize it. The function keyword is followed by a descriptive, user-defined name, followed by a set of curly braces to create a function. There’s a scriptblock within the curly braces that PowerShell should run.

You may see an example of a simple function and how to run it below. Install-Software is a function that utilizes Write-Host to show a message on the console. You may use the name of this function to run the code within its scriptblock after it’s declared.

PS> function Install-Software { Write-Host ‘I installed some software. Yippee!’ } PS> Install-Software I installed some software, Yippee!

Using Verb-Noun Naming

The naming of a function is crucial. You may give your functions whatever name you wish, but they should always explain what they perform. In PowerShell, the Verb-Noun syntax is used to name functions.

A verb should always come first in a function name, followed by a dash and a noun. Use the Get-Verb cmdlet to get a list of “authorized” verbs.

Functioning in a Different Way

If you wish to modify a function’s behavior, just update the code that it runs, as illustrated below.

PS> function Install-Software { Write-Host ‘You installed some software, Yay!’ } PS> Install-Software You installed some software, Yay!

The function will now show a slightly different message now that you’ve altered the code inside of it.

Creating a Complex Function

Functions may be defined in a variety of areas. The lesson assumes you copied and pasted the code straight into the PowerShell console in the previous step. However, this isn’t the only option. Functions may also be defined in a script.

Because you were dealing with a little function in the previous part, creating it in the console wasn’t too difficult. The most of the time, though, you’ll be dealing with considerably larger functions. It will be more convenient to define such functions in a script or module, then call that script or module to load the function into memory.

Retyping a bigger function every time you wish to change its functionality, as you would expect, may be tedious.

As you proceed through the remainder of the lesson, I recommend opening your preferred editor and saving the function as a.ps1 file.

Incorporating Parameters into Functions

PowerShell functions can have as many arguments as they want. When you write your own functions, you’ll be able to incorporate parameters and control how they’re used. The parameters may be required or optional, and they can take any argument or be compelled to accept one of a small number of options.

Related: PowerShell Parameters: Everything You Needed to Know

For example, the fictitious program you’re installing using the Install-Software function can come in many versions. However, the Install-Software function does not presently allow users to pick which version they wish to install.

You could update the code within the function each time you desired a different version if you were the only one using it, but that would be a waste of effort. This procedure would also be prone to mistakes, not to mention the fact that you want your code to be used by others.

By including arguments in your function, you may give it more flexibility. Parameters enable you to create a single function that accomplishes one thing in several ways, much as variables let you to construct scripts that can handle multiple variations of the same circumstance.

You want it to install several copies of the same piece of software on many machines in this situation.

Let’s start by adding a parameter to the function that allows you or a user to choose which version to install.

Making a Basic Parameter

A param block is required to create a parameter on a function. The param block contains all of the function’s arguments. As seen below, define a param block by using the param keyword followed by parentheses.

[CmdletBinding()] function Install-Software ‘I installed software version 2.’ param() Write-Host ‘Wheeeeeeeeeeeeeeeeee

The actual functionality of your function hasn’t changed at this moment. You’ve just finished installing the plumbing and setting up the function to accept a parameter.

For the time being, the function does not install any software. It’s just a case of utilizing the Write-Host cmdlet to mimic program installation so you can concentrate on designing the function.

After you’ve inserted the param block, you may construct the parameter by placing it within the parentheses of the param block, as seen below.

[CmdletBinding()] function Install-Software [Parameter()] param([Parameter()] param([Parameter()] par Write-Host ([string] $Version) “$Version is the program version I installed. What a relief! “,,,,,,,,,,

You’d start by defining the parameter block within the param block above. When you use the Parameter() block in this way, it becomes a “advanced parameter.” An empty parameter block, such as the one shown above, accomplishes nothing but is essential; in the following section, I’ll show you how to utilize it.

Instead, let’s concentrate on the [string] type before the parameter name. You cast the parameter’s value to a specified type by inserting the parameter’s type between square brackets before the parameter variable name. Any value supplied to this argument will be converted to a string by PowerShell if it isn’t already one. Anything given in as $Version will always be handled as a string in the example above.

It’s not necessary to cast your parameter to a type, but I strongly recommend it. It clearly describes the type and will help to minimize mistakes in the future.

You must now include $Version in your Write-Host declaration. This implies that if you use the Version option and supply a version number to the Install-Software method, you should see a message like the one below.

PS> Version 2 of Install-Software I installed software version 2. Yippee!

Let’s have a look at what this parameter can accomplish now.

Attribute for Mandatory Parameters

The parameter block may be used to modify numerous parameter properties, allowing you to alter the behavior of the parameter. For example, you might set an argument Mandatory if you want to make sure that everyone calling the method needs to send it in.

Parameters are optional by default. Let’s utilize the Mandatory keyword within the parameter block to compel the user to pass in a version, as seen below.

[CmdletBinding()] function Install-Software [Parameter(Mandatory)] param([Parameter(Mandatory)] param([Parameter(Mand $Version) ([string]$Version) ([string]$Version) ( Host-Write “$Version is the program version I installed. What a relief! “,,,,,,,,,,

You should receive the following prompt if you execute the method above:

A necessary parameter is being requested.A necessary parameter is being requested.

Executing the function without the argument after you’ve set the Mandatory attribute will block execution until the user submits a value. The function now waits for a value for the Version argument from the user. PowerShell runs the function after it is entered.

Simply supply a value to the argument when calling the function to skip the obligatory parameter prompt, as illustrated below.

Version 2 of Install-Software

Values of Default Parameters

You may create a default parameter value if you find yourself supplying the same value for a parameter over and over again, for example. When you anticipate a given value for a parameter most of the time, default parameters come in handy.

If you want to install version 2 of this program 90% of the time and don’t want to have to modify the value every time you execute this function, you could give the $Version argument a default value of 2. This is an example that you can see below.

[CmdletBinding()] function Install-Software [Parameter()] param([Parameter()] param([Parameter()] par [string] 2 ($Version) Host-Write “$Version is the program version I installed. What a relief! “,,,,,,,,,,

The presence of a default parameter does not exclude the addition of a new one. The value you’ve entered will take precedence over the default.

Adding Validation Attributes to Parameters

Limiting the values you can provide into a function through arguments is always a smart idea. Parameter validation characteristics are the most effective method to do this.

Limiting the information that users (or even you!) may send to your functions or scripts can help you avoid writing unneeded code. Consider the case when you supply the number 3 to your Install-Software method, knowing that version 3 is already in use.

Because your method believes that every user is aware of the different versions, it fails to account for what occurs when you attempt to provide version 4. The method will fail to locate the relevant folder in this example since it does not exist.

Life in the Absence of Parameter Validation

When using the $Version string in a file path, look at the example below. The function will fail if a value is supplied that does not complete an existing folder name (for example, SoftwareV3 or SoftwareV4).

Install-Software function param([Parameter(Mandatory)]) Get-ChildItem -Path SRV1InstallersSoftwareV$Version) Get-ChildItem -Path SRV1InstallersSoftwareV$Version) Get-ChildItem -Path SRV1InstallersSoftwareV$Version)

Failure due to unanticipated parameter valuesFailure due to unanticipated parameter values

To accommodate for this issue, you might implement error-handling code, or you could prevent it altogether by forcing the user to give only an existing version of the program. Add parameter validation to restrict the user’s input.

Adding Validation to Parameters

There are other types of parameter validation, but the [ValidateSet attribute](https://adamtheautomator.com/powershell-validateset/) works best for your Install-Software function. You may use the ValidateSet validation feature to define a list of valid values for a parameter. If you’re just accounting for the strings 1 and 2, make sure the user may only provide these values; otherwise, the function will fail and tell the user.

As illustrated below, add parameter validation characteristics within the param block, just under the original parameter block.

Install-Software function param([Parameter(Mandatory)]) [ValidateSet(‘1′,’2’)] Get-ChildItem -Path SRV1InstallersSoftwareV$Version) Get-ChildItem -Path SRV1InstallersSoftwareV$Version) Get-ChildItem -Path SRV1InstallersSoftwareV$Version)

By placing a set of items (1 and 2) between the ValidateSet attribute’s terminating parentheses, PowerShell is told that the only permissible values for Version are 1 and 2. If a user attempts to pass anything other than what’s in the set, they’ll get an error message like the one below, informing them that they only have a limited amount of alternatives.

The execution of a PowerShell function is halted due to parameter validation.The execution of a PowerShell function is halted due to parameter validation.

ValidateSet is a typical validation feature, although there are others as well. Check out the Microsoft documents for a comprehensive list of all the ways parameter values may be controlled.

Pipeline Input is Accepted

So far, you’ve created a function with a parameter that can be passed only by using the typical -ParameterName <Value> syntax. This works but you also have another option of passing values to parameters using the PowerShell pipeline. Let’s add pipeline capabilities to our Install-Software function.

Related: Pipeline Input is Accepted in the ATA PowerShell Parameters Article

To begin, add a new parameter to your code that indicates the machine on which the program will be installed. To replicate the installation, add that argument to your Write-Host reference.

Install-Software function param([Parameter(Mandatory)]) [string]$Version [ValidateSet(‘1′,’2’)], [Parameter(Mandatory)] [string]$Version [ValidateSet(‘1′,’2’)], [string]$Version [ValidateSet(‘1′,’ Write-Host ([string]$ComputerName) “On $ComputerName, I installed software version $Version. What a relief! “,,,,,,,,,,

You may now cycle through a list of computer names and send the values for the computer name and the version to the Install-Software function, as seen below, after adding the ComputerName argument to the function.

$computers = @(“SRV1”, “SRV2”, “SRV3”) foreach ($pc in $computers) { Version 2 of Install-Software -ComputerName $pc }

You should instead learn to utilize the pipeline instead of performing all of that.

Compatibility of the Function Pipeline

Unfortunately, using the PowerShell pipeline with only a basic function created before isn’t possible. You must choose the sort of pipeline input the function should receive and implement.

ByValue (the complete object) and ByPropertyName are the two types of pipeline input used by PowerShell functions (a single object property). Because the $computers array only includes strings, you’ll use ByValue to send those strings.

As illustrated below, add a parameter attribute to the parameter you wish to support pipelines by using one of two keywords: ValueFromPipeline or ValueFromPipelineByPropertyName.

Install-Software function param([Parameter(Mandatory)]) [ValidateSet(‘1′,’2’)] [string]$Version, [Mandatory, ValueFromPipeline)] [Parameter(Mandatory, ValueFromPipeline)] [Parameter(Mandatory, ValueFrom Write-Host ([string]$ComputerName) “On $ComputerName, I installed software version $Version. What a relief! “,,,,,,,,,,

Once you’ve loaded the update Instal-Software function, call it as follows:

$computers = @(“SRV1”, “SRV2”, “SRV3”) $computers | Version 2 of Install-Software

Rerun the script, and you should see something similar to this:

On SRV3, I installed software version 2. Yippee!

It’s worth noting that Install-Software only runs for the final string in the array. In the following part, you’ll learn how to solve this.

Adding a Block to a Process

You must add a process block to instruct PowerShell to run this function for every object that comes in. Put the code you wish to run every time the function gets pipeline input within the process block. As illustrated below, add a process block to your script.

Install-Software function param([Parameter(Mandatory)]) [ValidateSet(‘1′,’2’)] [string]$Version, [Mandatory, ValueFromPipeline)] [Parameter(Mandatory, ValueFromPipeline)] [Parameter(Mandatory, ValueFrom $ComputerName) process ([string]$ComputerName) process ([string]$ComputerName Write-Host is an acronym for “Write-Host is an acronym for ” “On $ComputerName, I installed software version $Version. What a relief! “‘ ‘

Now, call the function once more, exactly as you did before. Three lines will now be returned by the Install-Software function (one for each object).

I installed software version 2 on SRV1. Yippee! I installed software version 2 on SRV2. Yippee! On SRV3, I installed software version 2. Yippee!

The primary code you wish to run is in the process block. Begin and end blocks may also be used for code that runs at the start and end of a function call. The Microsoft documents include further information on the begin, process, and end blocks.

Steps to Follow

You may divide code into separate building units using functions. They not only assist you in breaking down your work into smaller, more manageable pieces, but they also push you to produce legible and tested code.

I now challenge you to go over some old scripts and find where a PowerShell function may be added. Look for recurring patterns in the code. Make a function out of the patterns. Take note of where you’re inserting code snippets and convert them to PowerShell functions!

The “powershell function in script” is a guide to help users understand how to write Powershell functions. The article also includes a list of the most common uses for Powershell functions.

Frequently Asked Questions

How do you use functions in PowerShell?

A: I would be happy to give you a detailed answer.

What are functions in PowerShell?

A: The functions in PowerShell are a set of commands that perform a specific task. For example, the Get-Process function is used to determine which processes are running on the computer and how much memory theyre using at this moment.

How do I get started with PowerShell?

A: PowerShell is a command line interface for Microsoft Windows, which can be used to automate tasks and execute scripts. It is an open source shell and scripting language with support for managing windows or servers by using the command prompt.

Related Tags

  • powershell function return
  • powershell functions examples
  • powershell custom functions
  • powershell call function in script
  • powershell call function with parameters

Table of Content