# Functions

Functions in PowerShell are reusable blocks of code that can accept parameters, return results, and even process piped input. They are essential for organizing and modularizing scripts, making them easier to read, maintain, and reuse.

***

#### **1. What is a Function?**

A **function** is a named block of code stored in the `function:\` drive. Functions can:

* Accept **parameters**.
* Return **results**.
* Process **piped input**.
* Be called from scripts or the interactive shell.

**Listing Functions**

To see all available functions in your session:

```
Get-ChildItem Function:\
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FbXqoAE0NoZnIiyljv4iF%2Fimage.png?alt=media&#x26;token=684747c0-f088-4156-93aa-f040699437df" alt=""><figcaption></figcaption></figure>

**Viewing Function Code**

To view the code of a specific function:

```
Get-Content Function:\mkdir
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FvIn1nPIEcucfAmsbKCjt%2Fimage.png?alt=media&#x26;token=b4f77682-85b0-4a1c-a55d-b8f0391fb00a" alt=""><figcaption></figcaption></figure>

Or:

```
Get-Item Function:\mkdir | Select-Object -ExpandProperty ScriptBlock
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FQZ664tn6S15MOV1jM7ra%2Fimage.png?alt=media&#x26;token=045e1e10-8fbe-4b77-a1ce-822ca8a7d8b9" alt=""><figcaption></figcaption></figure>

***

#### **2. Creating a Function**

**Basic Function**

A function is defined using the `function` keyword, followed by the function name and a script block (`{}`).

**Example:**

```
function Say-Hello {
    "Hello, World!"
}
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FNyx9sQcG40fdZcd6Jid2%2Fimage.png?alt=media&#x26;token=e4d2d68f-5448-4256-9e42-7840c055ec1c" alt=""><figcaption></figcaption></figure>

**Function with Parameters**

Functions can accept parameters, which are variables passed into the function when it is called.

**Example:**

```
function Greet-User {
    param (
        [string]$Name
    )
    "Hello, $Name!"
}
Greet-User -Name "Alice"
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2F8v0Tqdl3g2ygt73mCocg%2Fimage.png?alt=media&#x26;token=62c61c9f-67a4-4b36-94f3-4752a346ef47" alt=""><figcaption></figcaption></figure>

**Function with Multiple Parameters**

You can define multiple parameters and even assign default values.

**Example:**

```
function Add-Numbers {
    param (
        [int]$Number1,
        [int]$Number2 = 10
    )
    $Number1 + $Number2
}
Add-Numbers -Number1 5
```

***

#### **3. Advanced Function Features**

**Switch Parameters**

Switch parameters are boolean parameters that don’t require a value. They are either present (`$true`) or absent (`$false`).

**Example:**

```
function Test-Connection {
    param (
        [string]$ComputerName,
        [switch]$Ping
    )
    if ($Ping) {
        Test-Connection -ComputerName $ComputerName -Count 1
    } else {
        Test-NetConnection -ComputerName $ComputerName
    }
}
Test-Connection -ComputerName "server01" -Ping
```

**Default Parameter Values**

You can assign default values to parameters, which are used if no value is provided.

**Example:**

```
function Get-DiskUsage {
    param (
        [string]$Drive = "C:"
    )
    Get-Volume -DriveLetter $Drive
}
Get-DiskUsage
```

**Parameter Types**

You can enforce specific data types for parameters.

**Example:**

```
function Multiply-Numbers {
    param (
        [int]$Number1,
        [int]$Number2
    )
    $Number1 * $Number2
}
Multiply-Numbers -Number1 5 -Number2 3
```

***

#### **4. Processing Piped Input**

Functions can process objects piped into them using the `$input` variable or the `Process` block.

**Using `$input`**

The `$input` variable contains all piped objects.

**Example:**

```
function Process-Input {
    foreach ($item in $input) {
        "Processing: $item"
    }
}
1, 2, 3 | Process-Input
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FPRgLfG6krtXH0YP1xZ2V%2Fimage.png?alt=media&#x26;token=889d8e99-a8ab-491b-95b7-acea17d94cb4" alt=""><figcaption></figcaption></figure>

**Using the `Process` Block**

The `Process` block processes each piped object individually.

**Example:**

```
function Process-Input {
    process {
        "Processing: $_"
    }
}
1, 2, 3 | Process-Input
```

***

#### **5. Returning Results**

Functions return the output of their last executed command. You can use the `return` keyword to explicitly return a value and exit the function.

**Example:**

```
function Add-Numbers {
    param (
        [int]$Number1,
        [int]$Number2
    )
    return $Number1 + $Number2
}
$result = Add-Numbers -Number1 5 -Number2 3
```

***

#### **6. Error Handling**

You can control how errors are handled using the `-ErrorAction` parameter.

**Example:**

```
function Test-Connection {
    param (
        [string]$ComputerName
    )
    Test-Connection -ComputerName $ComputerName -ErrorAction SilentlyContinue
}
Test-Connection -ComputerName "nonexistent"
```
