Saturday, January 04, 2025

How To Write a PowerShell Portable Function

There are a few ways to write reusable PowerShell functions:

1. Script Modules (.psm1)

*   **Create a module file:** Create a new file with a `.psm1` extension (e.g., `MyFunctions.psm1`).

*   **Write your function:** Inside this file, define your function:

```powershell
function Get-MyThing {
   # Function code here
}

```

*   **Save the module:** Save the file in a directory that PowerShell can find. Common locations include:
   *   `$env:USERPROFILE\Documents\WindowsPowerShell\Modules\`
   *   `$env:PSModulePath` (system-wide modules)
*   **Import the module:** In your other scripts, import the module using:

```powershell
Import-Module MyFunctions
```

*   **Use the function:** You can now call `Get-MyThing` in your scripts.


2. Script Files (.ps1)

*   **Create a script file:** Create a new file with a `.ps1` extension (e.g., `MyFunctions.ps1`).

*   **Write your function:** Define your function within this script file.
*   **Dot source the script:** In your other scripts, use the dot sourcing operator (`.`) to load the functions:

```powershell
. .\MyFunctions.ps1
```

*   **Use the function:** You can now call your function.


3. Module Manifests (.psd1)

*   For more complex modules with multiple functions and dependencies, use a module manifest. This is a file with a `.psd1` extension that describes the module's contents, version, and other metadata.

*   You can use the `New-ModuleManifest` cmdlet to generate a basic manifest file.

Best Practices

  • Verb-Noun Naming: Use approved verbs (get, set, new, etc.) and descriptive nouns for your function names (e.g., Get-DiskSpace).
  • Parameters: Use parameters to make your functions flexible and reusable in different situations.
  • Comment-Based Help: Add comment-based help to your functions to provide documentation.
  • Error Handling: Include error handling with try-catch blocks to make your functions robust.
  • Output: Consider what your function will output. Raw data is generally preferred for functions, so it can be piped to other commands.

Example with Parameters and Help:

PowerShell

<#

.SYNOPSIS
Gets the free disk space on a computer.

.PARAMETER ComputerName
The name of the computer to check.

.EXAMPLE
Get-FreeDiskSpace -ComputerName "MyServer"
#>

function Get-FreeDiskSpace {
   
param(
       [
string]$ComputerName = "localhost"
   )

   
try {
       
Get-WmiObject Win32_LogicalDisk -ComputerName $ComputerName |
           
Where-Object {$_.DriveType -eq 3} |
           
Select-Object DeviceID, @{Name="FreeSpaceGB";Expression={$_.FreeSpace / 1GB}}
   }
   
catch {
       
Write-Error "Failed to get disk space: $_"

   }
}


By following these guidelines, you can create well-structured, reusable PowerShell functions that will improve the efficiency and maintainability of your scripts.

No comments: