Behind the PowerShell Pipeline logo

Behind the PowerShell Pipeline

Subscribe
Archives
June 27, 2023

PowerShell Functions 301

We’ve been looking at PowerShell functions, beginning with a simple basic function.

function Get-Uptime {
    $os = Get-CimInstance -ClassName Win32_OperatingSystem
    New-TimeSpan -Start $os.LastBootUpTime -End (Get-Date)
}

By the end of the last article, we had turned this into what I’d call an intermediate-level function. This version supports cmdletbinding so that we can use common cmdlet parameters like -Verbose. Of course, your function’s code needs to take advantage of this feature.

Function Get-ComputerUptime {
    [cmdletbinding()]
    [alias('gcup', 'cup')]
    [OutputType('PSCustomObject')]

    Param(
        [String]$ComputerName = $env:computername
    )

    Write-Verbose "[$((Get-Date).TimeOfDay)] Starting $($MyInvocation.MyCommand)"
    Write-Verbose "[$((Get-Date).TimeOfDay)] Running under PowerShell v$($PSVersionTable.PSVersion)"

    Try {
        Write-Verbose "[$((Get-Date).TimeOfDay)] Querying $($ComputerName.ToUpper()) for last boot up time"
        $os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName -ErrorAction Stop

        Write-Verbose "[$((Get-Date).TimeOfDay)] Last boot up time is $($os.LastBootUpTime)"
        $up = New-TimeSpan -Start $os.LastBootUpTime -End (Get-Date)
        [PSCustomObject]@{
            ComputerName = $os.CSName
            LastBoot     = $os.LastBootUpTime
            Uptime       = $up
        }
    } #Try
    Catch {
        Throw $_
    } #Catch
    Write-Verbose "[$((Get-Date).TimeOfDay)] Ending $($MyInvocation.MyCommand)"
} #close function
Want to read the full issue?
GitHub Bluesky LinkedIn About Jeff
Powered by Buttondown, the easiest way to start and grow your newsletter.