PowerShell Functions 201
Last time we started looking at creating a basic PowerShell function. The function is a command written in PowerShell’s scripting language that accomplishes a given task. The task can be described using a Verb-Noun naming convention. This will become the function’s name. To re-iterate key points, a PowerShell function does one thing and writes one type of object to the pipeline. Ideally, the output is a structured object that other PowerShell commands, like Select-Object
and ConvertTo-Json
can consume.
At the end of the previous article, I had completed this basic function.
function Get-ComputerUptime {
Param($ComputerName = $env:computername)
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName
$up = New-TimeSpan -Start $os.LastBootUpTime -End (Get-Date)
[PSCustomObject]@{
ComputerName = $os.CSName
LastBoot = $os.LastBootUpTime
Uptime = $up
}
}
When this function is loaded into my PowerShell session, I have an easy-to-use tool that writes a rich object to the pipeline.
Want to read the full issue?