Selected topic
Functions
Prefer practical output? Use related tools below while reading.
=====================================
PowerShell functions are reusable blocks of code that can be executed by calling their name. They allow you to encapsulate complex logic, reduce code duplication, and improve the readability and maintainability of your scripts.
A PowerShell function is defined using the function keyword, followed by the name of the function and any required parameters enclosed in parentheses:
powershell
function Get-Hello {
"Hello World!"
}Get-Hello is the name of the function.Create a function that prints a greeting message to the console:
powershell
function Greet {
param ($name)
"Hello, $name!"
}Greet -name "John"
# Output: Hello, John!
Greet is the name of the function.$name, which is a string."$name" with the actual value passed.Create a function that calculates the area and perimeter of a rectangle:
powershell
function Get-Rectangle {
param (
[int]$Width,
[int]$Height
)
$area = $Width * $Height
$perimeter = 2 * ($Width + $Height)
[PSCustomObject]@{
Area = $area
Perimeter = $perimeter
}
}$rect = Get-Rectangle -Width 10 -Height 20
$rect | Format-Table -Property *
# Output:
# Area Perimeter
# ---------- ----------
# 200 60
Get-Rectangle is the name of the function.$Width and $Height, which are integers.[PSCustomObject] containing the calculated properties.