Problem
You have commands in your script that you want to call multiple times, or a section of your script that you consider to be a “helper” for the main purpose of your script.
Solution
Place this common code in a function, and then call that function instead. For example, this Celsius conversion code in a script:
param([double] $fahrenheit)
## Convert it to Celsius $celsius = $fahrenheit 32 $celsius = $celsius / 1.8
## Output the answer "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
could be placed in a function (itself in a script):
param([double] $fahrenheit)
## Convert Fahrenheit to Celsius function ConvertFahrenheitToCelsius([double] $fahrenheit) {
$celsius = $fahrenheit 32 $celsius = $celsius / 1.8 $celsius
}
$celsius = ConvertFahrenheitToCelsius $fahrenheit
## Output the answer "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
Although using a function arguably makes this specific script longer and more difficult to understand, the technique is extremely valuable (and used) in almost all nontrivial scripts.
Discussion
Once you define a function, any command after that definition can use it. This means that you must define your function before any part of your script that uses it. You might find this unwieldy if your script defines many functions, as the function definitions obscure the main logic portion of your script.
Acommon question that comes from those accustomed to batch scripting in cmd.exe is, “What is the PowerShell equivalent of a GOTO?” In situations where the GOTO is used to call subroutines or other iso
lated helper parts of the batch file, use a PowerShell function to accomplish that task. If the GOTO is used as a way to loop over something, PowerShell’s looping mechanisms are more appropriate.
In PowerShell, calling a function is designed to feel just like calling a cmdlet or a script. As a user, you should not have to know whether a little helper routine was written as a cmdlet, script, or function. When you call a function, simply add the parameters after the function name, with spaces separating each one (as shown in the solution). This is in contrast to the way that you call functions in many programming languages (such as C#), where you use parentheses after the function name and commas between each parameter.
Also, notice that the return value from a function is anything that it writes to the output pipeline (such as $celsius in the solution). You can write return $celsius if you want, but it is unnecessary.