An advanced function is a PowerShell function marked with [CmdletBinding()]. That single attribute gives it cmdlet-like behavior, including common parameters such as -Verbose, -Debug, -ErrorAction, and -OutVariable. section 11.1
Build advanced functions by combining several parameter and execution features:
- Accept pipeline input by value or by property name with Parameter attributes. section 11.1.1
- Process pipeline data in BEGIN, PROCESS, and END blocks; use BEGIN for setup and PROCESS for each incoming object. section 11.1.1
- Add mandatory parameters, validation, aliases, and -Confirm or -WhatIf support for safer, more predictable commands. section 11.3
Pipeline-ready machine information
A Get-MachineInfo function can accept ComputerName directly or from the pipeline, establish a session in PROCESS, query operating-system data, and remove the session afterward. For example: Get-MachineInfo -ComputerName ONE,TWO,THREE or "ONE","TWO","THREE" | Get-MachineInfo. section 11.1.1
Listing 11.2 Modified Get-MachineInfo
function Get-MachineInfo {
[CmdletBinding()] #1
Param(
[Parameter(ValueFromPipeline=$True)] #2
[string[]]$ComputerName,
[string]$LogFailuresToPath,
[string]$Protocol = "Wsman",
[switch]$ProtocolFallback
)
BEGIN {} #3
PROCESS {
foreach ($computer in $computername) {
# Establish session protocol
if ($protocol -eq 'Dcom') {
$option = New-CimSessionOption -Protocol Dcom
} else {
$option = New-CimSessionOption -Protocol Wsman
}
# Connect session
$session = New-CimSession -ComputerName $computer `
-SessionOption $option
# Query data
$os = Get-CimInstance -ClassName Win32_OperatingSystem `
-CimSession $session
# Close session
$session | Remove-CimSession
# Output data
$os | Select-Object -Prop @{n='ComputerName';e={$computer}},
Version,ServicePackMajorVersion
} #foreach
} #PROCESS
END {}
} #function
Inspect the modified Get-MachineInfo implementation to see CmdletBinding, pipeline binding, and BEGIN/PROCESS structure applied together. section 11.1.1
