Functions and Modules

The Function Library That Saved My Team

I noticed our team was copying the same PowerShell code across dozens of scripts: logging functions, error handling, configuration loading. Every script had its own slightly different version, making maintenance a nightmare.

I spent a weekend creating a shared module with all our common functions:

Import-Module CompanyTools

Write-CompanyLog "Starting deployment"
$config = Get-CompanyConfig -Environment "Production"
Test-CompanyConnectivity -ServerList $config.Servers

One module, 200+ scripts now using it. A bug fix in the module fixed it everywhere. That's the power of functions and modules.

Functions

Functions are reusable code blocks.

Basic Function

function Get-ServerUptime {
    $os = Get-CimInstance -ClassName Win32_OperatingSystem
    $uptime = (Get-Date) - $os.LastBootUpTime
    Write-Host "Server uptime: $($uptime.Days) days, $($uptime.Hours) hours"
}

# Call it
Get-ServerUptime

Functions with Parameters

Return Values

Advanced Functions

Add cmdlet-like features with [CmdletBinding()].

CmdletBinding

Pipeline Input

Parameter Sets

Creating Modules

Modules package related functions.

Script Module (.psm1)

Using the Module

Module Manifest (.psd1)

Installing Modules

Module Paths

PowerShell looks for modules in these paths:

Real-World Module Example

Key Takeaways

  • Functions encapsulate reusable code

  • [CmdletBinding()] adds cmdlet features

  • Modules (.psm1) package related functions

  • Manifests (.psd1) describe modules

  • PowerShell Gallery hosts public modules

  • Export-ModuleMember controls visibility

What You've Learned

✅ Creating basic and advanced functions ✅ Using CmdletBinding for cmdlet-like features ✅ Building script modules (.psm1) ✅ Creating module manifests (.psd1) ✅ Installing modules from PowerShell Gallery ✅ Real-world module patterns

Next Steps

Now you can create reusable code. Let's scale up. In PowerShell Remoting and Automation, you'll learn:

  • PowerShell remoting (WinRM, SSH)

  • Managing multiple servers

  • Background jobs

  • Parallel execution

Manage hundreds of systems from one console.


Ready for remoting? Continue to PowerShell Remoting and Automation

Last updated