0
0
PowerShellscripting~5 mins

Function definition in PowerShell

Choose your learning style9 modes available
Introduction
Functions let you group commands together to reuse them easily. They help keep your scripts neat and save time.
When you want to run the same set of commands multiple times.
To organize your script into smaller, understandable parts.
When you want to make your script easier to read and maintain.
To avoid repeating code and reduce mistakes.
When you want to pass information to a set of commands and get results back.
Syntax
PowerShell
function FunctionName {
    # commands go here
}
Function names should be clear and describe what they do.
Use curly braces { } to group the commands inside the function.
Examples
A simple function that prints 'Hello, world!' when called.
PowerShell
function SayHello {
    Write-Output "Hello, world!"
}
A function that takes two numbers and returns their sum.
PowerShell
function Add-Numbers {
    param($a, $b)
    return ($a + $b)
}
Sample Program
This script defines a function named Greet that takes a name and prints a greeting. Then it calls the function with 'Alice'.
PowerShell
function Greet {
    param($name)
    Write-Output "Hello, $name!"
}

Greet -name "Alice"
OutputSuccess
Important Notes
You call a function by its name and provide any needed parameters.
Functions help avoid repeating the same code in different places.
Use 'param' inside functions to accept inputs.
Summary
Functions group commands to reuse them easily.
Define functions with 'function Name { }' and use 'param' for inputs.
Call functions by their name to run the grouped commands.