Selected topic

Functions in PowerShell

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.

Why Use Functions?


------------------------

  1. Code Reusability: Write code once and use it multiple times.
  2. Modularity: Break down large scripts into smaller, independent functions.
  3. Improved Readability: Reduce code clutter by grouping related logic.
  4. Easier Maintenance: Modify a function in one place, rather than searching for its usage throughout the script.

Basic Syntax

----------------

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!"
}

In this example:

  • Get-Hello is the name of the function.
  • The function takes no arguments.

Example 1: Simple 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!


In this example:

  • Greet is the name of the function.
  • The function takes one argument, $name, which is a string.
  • The function uses parameter binding to replace the placeholder "$name" with the actual value passed.

Example 2: Function with Multiple Parameters

-------------------------------------------------

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


In this example:

  • Get-Rectangle is the name of the function.
  • The function takes two arguments, $Width and $Height, which are integers.
  • The function uses parameter binding to calculate the area and perimeter based on the provided values.
  • The function returns a [PSCustomObject] containing the calculated properties.
These examples demonstrate the basic syntax and usage of functions in PowerShell. By following best practices for function naming, parameterization, and output formatting, you can create reusable and maintainable code that improves your productivity and reduces errors.