PowerShell Functions:
Defining a function:
To define a function, use the 'function' keyword followed by the function name and a script block containing the code to be executed when the function is called.
function MyFunction {
# Code to execute when the function is called
}
Adding parameters:
You can define parameters for your function by adding a 'param' block at the beginning of the script block. This allows you to pass arguments to the function when it's called.
function MyFunctionWithParams {
param (
$Param1,
$Param2
)
# Code to execute using $Param1 and $Param2
}
Adding default values and parameter types:
You can specify default values for your parameters and enforce parameter types to ensure the function receives the expected input.
function MyFunctionWithDefaultsAndTypes {
param (
[string]$Param1 = "DefaultValue",
[int]$Param2 = 42
)
# Code to execute using $Param1 and $Param2
}
Returning values:
To return a value from a function, you can use the 'return' keyword, or you can simply output a value, which will be captured as the function's return value.
function MyFunctionReturnsValue {
param (
$InputValue
)
$OutputValue = $InputValue * 2
# Return the value
return $OutputValue
}
Calling a function:
To call a function, simply use the function's name followed by the arguments in parentheses, separated by commas.
# Call the function without parameters
MyFunction
# Call the function with parameters
MyFunctionWithParams -Param1 "Hello" -Param2 "World"
# Call the function and capture the return value
$result = MyFunctionReturnsValue -InputValue 10
Functions are an essential part of PowerShell scripting, allowing you to create more organized, modular, and maintainable scripts.