You define a function in PowerShell using the function
keyword followed by the function name and a set of curly braces ({}
) that enclose the function's code.
Here's a basic example:
function Greet-User {
Write-Host "Hello, World!"
}
This function, named Greet-User
, simply prints "Hello, World!" to the console.
Here's a more detailed breakdown:
Defining a PowerShell Function
function
Keyword: This keyword signals that you're defining a function.- Function Name: Choose a descriptive name for your function, following PowerShell's naming conventions (e.g., use verbs and nouns).
- Curly Braces (
{}
): These enclose the code that the function will execute.
Example with Parameters
Functions can accept parameters to make them more versatile. For example:
function Greet-User {
param([string]$name)
Write-Host "Hello, $name!"
}
Greet-User -name "John"
In this example, the Greet-User
function takes a $name
parameter, which is used to personalize the greeting.
Returning Values
Functions can return values using the return
keyword:
function Add-Numbers {
param([int]$num1, [int]$num2)
return $num1 + $num2
}
$result = Add-Numbers -num1 5 -num2 10
Write-Host "The sum is: $result"
This function Add-Numbers
takes two integer parameters and returns their sum.
Practical Insights
- Functions help you organize your PowerShell scripts by breaking down complex tasks into smaller, reusable units.
- Parameters allow you to make your functions more flexible and adaptable to different scenarios.
- Returning values enables you to use the results of your functions in other parts of your script.