Saturday, January 04, 2025

How To Write a PowerShell Portable Function

How to Write Reusable PowerShell Functions

1. Script Modules (.psm1)

  1. Create a module file:
  1. Create a new file with a `.psm1` extension (e.g., `MyFunctions.psm1`).
  2. Write your function:  Inside this file, define your function:

#PowerShell
function Get-MyThing {
   
# Function code here
}

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

#powershell
Import-Module MyFunctions

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

2. Script Files (.ps1)

  1. Create a script file: Create a new file with a `.ps1` extension (e.g., `MyFunctions.ps1`).
  2. Write your function:  Define your function within this script file.
  3. Dot source the script: In your other scripts, use the dot sourcing operator (`.`) to load the functions:

# PowerShell
. .\MyFunctions.ps1

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

3. Module Manifests (.psd1)

Use a module manifest for more complex modules with multiple functions and dependencies. This is a file with a `.psd1` extension that describes the module's contents, version, and other metadata.  The `New-ModuleManifest` cmdlet can 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: Use 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: