Public/Get-Uptime.ps1

Function Get-Uptime
{
        <#
            .EXTERNALHELP HelperFunctions.psm1-Help.xml
        #>

    
    
    [CmdletBinding()]
    [OutputType([pscustomobject])]
    Param
    (
        [Parameter(Mandatory = $false)]
        [string]$ComputerName = [System.Net.Dns]::GetHostByName("LocalHost").HostName,
        [Parameter(Mandatory = $false)]
        [System.Management.Automation.PsCredential]$Credential
    )
    
    Begin
    {
        #Enable TLS 1.2 and 1.3
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls13
        
        [String]$dtmFormatString = "yyyy-MM-dd HH:mm:ss"
        $ns = 'root\CIMv2'
    }
    Process
    {
        $thisHost = [System.Net.Dns]::GetHostByName("LocalHost").HostName
        
        $params = @{
            ComputerName = $ComputerName
            NameSpace    = $ns
            ErrorAction  = 'Continue'
        }
        
        If (($PSBoundParameters.ContainsKey('Credential') -eq $true) -and ($PSBoundParameters['Credential'] -ne $null))
        {
            $params.Add('Credential', $Credential)
        }
        
        If ($ComputerName -eq $thisHost)
        {
            Try
            {
                $objOS = Get-CimInstance -ClassName Win32_OperatingSystem -Namespace $ns -ErrorAction Continue
            }
            Catch
            {
                $objOS = Get-WmiObject -Class Win32_OperatingSystem -Namespace $ns -ErrorAction Continue
            }
        }
        ElseIf ($ComputerName -ne [System.Net.Dns]::GetHostByName("LocalHost").HostName -and $Credential -eq $null)
        {
            Try
            {
                $objOS = Get-CimInstance -ClassName Win32_OperatingSystem @params
            }
            Catch
            {
                $objOS = Get-WmiObject -Class Win32_OperatingSystem @params
            }
        }
        Else
        {
            Throw "unknown error"
        }
        
        If ($objOS -ne $null)
        {
            $uptimeTimespan = New-TimeSpan -Start ($objOS.ConvertToDateTime($objOS.LastBootUpTime)).ToUniversalTime() -End ($objOS.ConvertToDateTime($objOS.LocalDateTime)).ToUniversalTime()
            $uptime = New-Object System.TimeSpan($uptimeTimespan.Days, $uptimeTimespan.Hours, $uptimeTimespan.Minutes, $uptimeTimespan.Seconds)
            $lastBootupTime = ($objOS.ConvertToDateTime($objOS.LastBootUpTime)).ToString($dtmFormatString)
            $lastBootupTimeUTC = (($objOS.ConvertToDateTime($objOS.LastBootUpTime)).ToUniversalTime()).ToString($dtmFormatString)
        }
    }
    End
    {
        Return [PSCustomObject]@{
            Computer            = $ComputerName
            Uptime           = $uptime
            LastBootTimeUTC   = $lastBootupTimeUTC
            LastBootTimeLocal = $lastBootupTime
        }
    }
} #End function Get-Uptime