PoshCode Archive  Artifact [7ba470f273]

Artifact 7ba470f273d63c75bc7a82de8352d2be80eee58b46e8f90ce0e86dd182825987:

  • File 2-ways-in-1-get-uptime.ps1 — part of check-in [36bc41777c] at 2018-06-10 13:43:24 on branch trunk — Combines two technics to get last boot system uptime (user: greg zakharov size: 1179)

# encoding: ascii
# api: powershell
# title: 2 ways (in 1) get uptime
# description: Combines two technics to get last boot system uptime
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Get-SystemUptime
# x-poshcode-id: 4586
# x-archived: 2013-12-05T12:39:29
# x-published: 2013-11-06T08:25:00
#
#
#requires -version 2.0
Set-Alias uptime Get-SystemUptime

function Get-SystemUptime {
  <#
    .SYNOPSIS
        Returns uptime of system.
    .DESCRIPTION
        Actually, this demo shows that you don't need an access to Win32_OperatingSystem
        to get system last boot uptime.
  #>
  [CmdletBinding()]
  param()
  
  begin {
    $usr = [Security.Principal.WindowsIdentity]::GetCurrent()
    $res = (New-Object Security.Principal.WindowsPrincipal $usr).IsInRole(
      [Security.Principal.WindowsBuiltInRole]::Administrator
    )
  }
  process {
    switch ($res) {
      $true{
        $wmi = gwmi Win32_OperatingSystem
        New-TimeSpan $wmi.ConvertToDateTime($wmi.LastBootUpTime) (Get-Date)
      }
      $false{[TimeSpan]::FromMilliseconds([Environment]::TickCount)}
    }
  }
  end{}
}