Passing variables to functions
One of the most powerful features of PowerShell functions is in using variables to pass data into the function. By passing data into a function, the function can be more generic, and can perform actions on many types of objects.
In this recipe, we will show how to accept variables in functions, and how to report errors if a mandatory variable is not included.
How to do it...
For this recipe we will be using the following function.
Function Add-Numbers { Param( [int]$FirstNum = $(Throw "You must supply at least 1 number") , [int]$SecondNum = $FirstNum ) Write-Host ($FirstNum + $SecondNum) }
How it works...
At the beginning of the function we reference the Param()
keyword which defines the parameters the function will accept. The first parameter, $FirstNum
, we define as being mandatory and of type [int]
or integer. We did not have to classify the parameter type, and the function would have worked without this, but it's a good practice to validate the input of your functions.
The second parameter, $SecondNum
, is also typed as [int]
, but also has a default value defined. This way if no value is passed for the second parameter, it will default to the $FirstNum
.
When the function runs, it reads in the parameters from the command line and attempts to place them in the variables. The parameters can be assigned based on their position in the command line (that is, the first number is placed into $FirstNum
, and the second number is placed into $SecondNum
). Additionally, we can call the function using named parameters with the –FirstNum
and –SecondNum
switches. The following screenshot gives an example of this:
If a parameter has a Throw
attribute assigned, but the value is not provided, the function will end and return an error. Additionally, if a parameter has a type defined, but the value received is incompatible (such as a string being placed into an integer), the function will end and return an error.
There's more...
Functions are not only capable of receiving input, but also returning output. This ability can come in very handy when trying to return values into other variables instead of simply returning the values to the screen. In our example, we can replace our Write-Host
command with a Return
command.
#Write-Host ($FirstNum + $SecondNum) Return ($FirstNum + $SecondNum)
The output of the function is mostly the same, except now we can assign the output to a variable and use that variable at a later time.
Note
In addition to returning values from functions, Return
also causes the function to exit. The Return
command should always be placed at the end of a function, or at a point where processing of the function should stop.