Cmdlets & Functions
PowerShell cmdlets and functions are the building blocks of automation, enabling you to encapsulate logic, enforce validation, and provide clear documentation for reusable code. This section guides you through creating custom cmdlets and functions, with a focus on parameter validation and help documentation to ensure robust and maintainable scripts.
Creating Custom Cmdlets¶
Cmdlets are reusable PowerShell components that perform specific tasks. While creating cmdlets typically involves the Windows SDK and C#, you can also define cmdlet-like behavior using PowerShell functions with attributes. For advanced cmdlet development, use the New-Module cmdlet and a module manifest (*.psd1) to register cmdlets. For example:
# Example: Module manifest (MyModule.psd1)
@{
RootModule = 'MyModule.psm1'
CmdletsToExport = 'Get-ServiceStatus'
FunctionsToExport = 'Test-PortAvailability'
Guid = 'a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8'
}
For simpler scenarios, use PowerShell functions with attributes to mimic cmdlet behavior.
Creating Custom Functions¶
Functions are the primary way to create reusable logic in PowerShell. Define them using the function keyword. Here's a basic example:
function Get-ServiceStatus {
[CmdletBinding()]
param (
[string]$ServiceName
)
$service = Get-Service -Name $ServiceName -ErrorAction Stop
return [PSCustomObject]@{
Name = $service.Name
Status = $service.Status
Started = $service.Started
}
}
Key Elements:¶
[CmdletBinding()]: Enables advanced features like error handling and parameter validation.param(): Defines input parameters.[PSCustomObject]: Returns structured data.
Parameter Validation¶
Validate inputs to prevent errors and ensure correctness. Use the Validate attributes or custom validation logic:
Built-in Validation Attributes¶
Custom Validation Function¶
function Test-ValidPort {
param ([int]$Port)
return $Port -ge 1 -and $Port -le 65535
}
param (
[ValidateScript({ Test-ValidPort $_ })]
[int]$Port
)
For complex validation, use ValidateCount, ValidateRange, or ValidatePattern.
Help Documentation¶
Add clear documentation using comment-based help (.SYNOPSIS, .DESCRIPTION, etc.):
<#
.SYNOPSIS
Checks if a service is running.
.DESCRIPTION
Retrieves the status of a Windows service and returns a custom object.
.PARAMETER ServiceName
The name of the service to check.
.EXAMPLE
Get-ServiceStatus -ServiceName "Spooler"
#>
function Get-ServiceStatus {
[CmdletBinding()]
param (
[string]$ServiceName
)
# Function implementation
}
Use Get-Help to view the documentation:
Key takeaways¶
- Use functions for simple, reusable logic and cmdlets for advanced, registered modules.
- Validate parameters with attributes or custom functions to ensure robustness.
- Document functions with comment-based help for clarity and usability.
- Combine advanced features like error handling and structured output for professional-grade automation.