All PowerShell functions can have one or more parameters. If you're not using parameters in your PowerShell functions, you're not writing PowerShell right at all. Learn the ins, outs and in between in this long blog post demystifying the PowerShell parameter. When you begin to create your own functions, you'll have the option to include parameters or not and how those parameters work.
Let's say you have a function that installs Microsoft Office. Maybe it calls the Office installer silently inside of the function. What the function does, doesn't matter for our purposes. The basic function looks like this with the name of the function and the script block with all of the goodies to soon be inside.
In this example, you just ran Install-Office without parameters and it does it's thing. It didn't matter whether the Install-Office function had parameters or not. It apparently didn't have any mandatory parameters else PowerShell would not have let us run it without using a parameter.
Office has lots of different versions. Perhaps you need to install Office and Currently, you have no way to specify this. You could change the function's code every time you wanted to change the behavior. Doing this work but it's not scalable and forces you to create a separate function for every single version of PowerShell that comes out. You're going to have to duplicate lots of code when you don't have to. Instead, you need a way to pass in different values at runtime to change the behavior of the function.
How do you do this? Since we'd like to install different versions of Office without having to change the code every time, you have to add at least one parameter to this function. Before you just quickly think up a parameter to use, it's essential first to ask yourself a question, "What is the smallest change or changes you expect will be needed in this function?
Remember that you need to rerun this function without changing any of the code inside of the function. In this example, the parameter is probably clear to you; you need to add a Version parameter. But, when you've got a function with tens of lines of code that performs various tasks, the answer won't be too apparent. As long as you answer that question as precisely as possible, it will always help.
So you know you need a Version parameter. Now what?Microsoft PowerShell for Beginners - Video 1
You now can add one, but like any great programming language, there are multiple ways to skin that cat. Because this isn't meant to be a comprehensive PowerShell tutorial, I'll be showing you the "best" way to create parameters based on my nearly decade of experience with PowerShell.You can add parameters to the advanced functions that you write, and use parameter attributes and arguments to limit the parameter values that function users submit with the parameter.
The parameters that you add to your function are available to users in addition to the common parameters that PowerShell adds automatically to all cmdlets and advanced functions. Beginning in PowerShell 3. Splatting is valid on simple and advanced functions. When you supply strings as arguments to parameters that expect a different type, PowerShell implicitly converts the strings to the parameter target type. Advanced functions perform culture-invariant parsing of parameter values. By contrast, a culture-sensitive conversion is performed during parameter binding for compiled cmdlets.
In this example, we create a cmdlet and a script function that take a [datetime] parameter. The current culture is changed to use German settings. A German-formatted date is passed to the parameter. Static parameters are parameters that are always available in the function. Most parameters in PowerShell cmdlets and scripts are static parameters.
The following example shows the declaration of a ComputerName parameter that has the following characteristics:. All attributes are optional. However, if you omit the CmdletBinding attribute, then to be recognized as an advanced function, the function must include the Parameter attribute. You can add one or multiple attributes in each parameter declaration.
There's no limit to the number of attributes that you can add to a parameter declaration. The Parameter attribute is used to declare the attributes of function parameters. The Parameter attribute is optional, and you can omit it if none of the parameters of your functions need attributes.
But, to be recognized as an advanced function, rather than a simple function, a function must have either the CmdletBinding attribute or the Parameter attribute, or both. The Parameter attribute has arguments that define the characteristics of the parameter, such as whether the parameter is mandatory or optional.
Use the following syntax to declare the Parameter attribute, an argument, and an argument value. The parentheses that enclose the argument and its value must follow Parameter with no intervening space. Use commas to separate arguments within the parentheses. Use the following syntax to declare two arguments of the Parameter attribute.
If you use the Parameter attribute without arguments, as an alternative to using the CmdletBinding attribute, the parentheses that follow the attribute name are still required.When you are writing a PowerShell script or function you often want to accept user input via parameters. If you don't limit the values those parameters accept, you can guarantee that there will be situations where inappropriate values are supplied. In this article, learn how to use the ValidateSet parameter validation attribute to limit those values to only ones you define.
This article focuses on the ValidateSet validation attribute. You will learn what ValidateSet does, why you might want to use ValidateSet in your code and how to do so. You will also learn about the tab-completion feature that is enabled by ValidateSet and will help users of your code provide valid parameter values.
ValidateSet is a parameter attribute that allows you to define a set of elements that are only accepted as the value for that parameter. For example, perhaps, you have a script that is defined to work with Active Directory domain controllers. This script has a parameter that specifies the name of a domain controller. Wouldn't it make sense to limit the list of acceptable values to the actual names of the domain controllers?
There's no reason the user should be able to use "foobar" as a value when you know beforehand what values the script neds. ValidateSet gives you that capability. This article will be a learning walkthrough. If you plan to follow along, you will need the following:. This script returns information about the sizes of planets in our solar system. You will start off with a simple script and gradually improve its ability to handle input from the end-user and make discovery of its possible parameter values easy for them.
To get started, first copy and paste the PowerShell code below into your favorite text editor and save it as Get-PlanetSize. Informative but not very flexible; the information for every planet is returned, even if you only want the information for Mars. Perhaps you'd like the capability to specify a single planet instead of returning all of them. You'd do that by introducing a parameter. To allow the script to accept a parameter, add a Param block to the top of the script. Call the parameter Planet.
A suitable Param block looks like below. In the example below, the line [Parameter Mandatory ] ensures that a planet name is always supplied to the script. Now you're not relying on the hashtable statically defined earlier and instead are reading the value of the Planet parameter. Now if you run the script and specify a planet using the Planet parameter, you only see information about that particular planet.
What happens if you try to find the diameter of the planet Barsoom using Get-PlanetSize. How can we fix this? The script needs a way to limit which values are accepted for the Planet parameter.
Simplify Your PowerShell Script with Parameter Validation
Enter ValidateSet! A ValidateSet list is a comma-separated list of string values, wrapped in single or double-quotes. Adding a ValidateSet attribute to a script or function parameter consists of adding a line of text to the Param block, as shown below. Replace the Param block in your copy of Get-PlanetSize.
Try running the script again using Barsoom as your Planet parameter. Now a helpful error message is returned. The message is specific in what went wrong and even provides a list of possible values for the parameter.
By default, the ValidateSet attribute is case insensitive. This means that it will allow any string granted it's in the allowed list with any capitalization scheme.There are two types of PowerShell Functions, basic and advanced. 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. 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. 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 BeginProcess and End blocks. This section covers the first stage in writing a Powershell Function: defining the function block.
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:. 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. To work with the credential, I will use the Get-Credential cmdlet to extract the credential.
Take 10% Off
But because this parameter is optional, I will add an IF statement as shown below. The Process block is where you add the main scripts for the function. In this instance, this block contains the Get-ADUser cmdlet. Writing a PowerShell function may appear complex but it is actually easy. I hope this guide simplified it for you. You could also share your PowerShell scripting experience with other readers. Great success with this site! Sign in. Log into your account.
How to Clear Clipboard on Android. How to Clear Clipboard on Windows Microsoft Scripting Guy Ed Wilson here. After we had chatted for about a half an hour or so, it was time to get ready for my presentation to the group.
Scripto TV efforts. I am really hoping to make it for All of my community events such as talking to various users groups are listed on the Scripting Community page of the TechNet Script Center.
I keep that pretty well up to date, so you can always see where I will be speaking and plan accordingly. Anyway, after I rang off the Live Meeting, I got back to work on a module I needed for my desktop automation project.
I came up with a pretty good Local User Management Module. The Local User Management Module is a Windows PowerShell module that contains a number of functions that enable, disable, create, delete, and modify users and groups. The following functions are contained in the module:. Each function is complete with help and therefore to find out how to use New-LocalGroupyou would use one of the commands seen here.
The full parameter causes all of the help information to display. The examples parameter causes help to return only example information. The difference between detailed and full is subtle—complete parameter information is returned when full is specified, but only partial parameter information is returned when using the detailed parameter. Blog post, is I created a couple of named parameter sets. By doing this, I was able to simplify my code.
Let me explain. In the Set-LocalGroup function, I wanted to be able to either add or remove a local user to a local group. I wanted to have both add and remove switches. Obviously I do not want to include both add and remove on the same command line. However, to be a valid command, either add or remove must be specified. If I tried to do manual command-line checking, it could be a bit complicated, but by using two parameter sets, it is easy.
Here is the parameter declaration for the function. If I attempt to call the Set-LocalGroup function without using either add or removean error appears that states that the parameter set cannot be resolved. The error is essentially stating that Windows PowerShell cannot tell how to call the command. Set-LocalGroup : Parameter set cannot be resolved using the specified named parameters.
The command and associated error are shown here:. In addition to having an enable and a disable parameter, I also have a password parameter that is only needed if I also use the enable parameter. The scenario is similar to the one I had with Set-LocalGroupexcept that one of the command will also appear with an additional parameter.
The difference is that two of the parameters use the same parameter set name because they will be used together. The complete param declaration appears here:. I uploaded the complete module to the Scripting Guys Script Repository.Summary : Learn how to simplify your Windows PowerShell Script by using parameter validation attribute. Microsoft Scripting Guy, Ed Wilson, is here.
Glenn started scripting early in his IT career, and he has made a living off it ever since. Along the way, he started a blogwrote a bookand is the proud father of two beautiful children. This resulted in a hundreds of thousands of lines of Windows PowerShell code, some better than others, but all executed to the authors best ability.
Fortunately with Windows PowerShell, almost all mishaps were a result of the author simply not knowing about or how to use a feature within the Windows PowerShell language. Today, we will try to shed light on a feature that was introduced in Windows PowerShell 2. In this example, you have three parameters NameAgeand Path.
For the script to function correctly, you need the Name to be Tom, Dick, or Jane. The Age parameter must be between 21 and 65, and the Path parameter must point to a valid folder.
In Windows PowerShell 1. There are several drawbacks to this approach. First of all, you had to dedicate a chunk of the script to validating the value of each parameter. The validation is only as good as the script written to check it. There is also the issue of the error messages. These too, are only as good as written—and we all know how much we like to write good verbose messages.
Even if you do write a good descriptive error message, it does not point to the problem in the code. The error points to the throw statement in the code, so it is not very intuitive. Finally, if you ever want to make any modifications to the accepted parameter values, you would have to change those values in multiple places within the script.
For all these reasons and more, the Windows PowerShell team introduced parameter validation. Let us take a look at the previous example with parameter validation. First of all, you replace over 10 lines of code with three markup tags! More importantly, look at the output that is received when using the built-in validation tools:. Clean, verbose, and meaningful error messages are generated for free. You do not have to write anything! More importantly, if you wanted to adjust the accepted values, you only have to change them in one place.
The toolbox available to you for parameter validation is vast and flexible. Currently, there are eleven dedicated parameter validation attributes that cover just about everything.
Create dynamic PowerShell functions with Parameter Sets
However, like everything in life, there are flaws in the system. For instance, if you assign a default value to a parameter, that value will not be validated because only passed parameters are validated.
This is shown in the following example:. Intuition would imply that this code would throw an error if we attempt to use the default value—but remember, only user-supplied values are validated. Although inconsistent, this is understandable because the validation attributes are only run during parameter binding, and the default value is processed after parameter binding has occurred.
Of course, this really is not that big of a deal. You just have to know about the limitation, and script around it.A script that never changes and has static values may not need parameters, but to really improve your scripts, you will want to add parameters to allow them to evolve and be multipurpose.
You can hard code the name of the computer in the script, along with a domain controller, the email server and the recipients of the email in the script. But what if you want to use that script in other companies or the server names change in the future?
You could open the script each time you want to change something, modify the values, save it and then run it. Or, you can add parameters to allow for changes without modifying your script each time. But what if you want to change the name to someone else? You would have to open the script and manually change the name to something else. By adding a block of code at the top of your script called a param block, you can add a parameter to pass into the script.
As you can see in the output, our message never gets displayed, no matter what we do.
We can now start to get fancy by declaring what the parameter should be. So far, the parameters have always been unspecified. But we are going to change our code a little and try some basic math. Well, not what I expected, but that might be useful for other purposes.
By declaring the variable type in the param block, I can force users into better inputs. Making sure to declare the variable type in the param block will ensure that your expected variables are of the type you wanted. You can also add more detailed checks to your parameters. The first time I ran the script, everything worked as expected. The last thing I want to talk about is setting default values for your parameters. I can change the value of the parameter each time I run the script.
By doing so, I turned this into a tool that can run against a single computer or multiple computers.