Tuesday, 22 December 2015

Uptime/Countdown PowerShell Script

I originally wrote this script because I thought my Windows Server 2012 R2 Standard Evaluation was close to expiring, and I was preparing for it shutting down every hour or so, but I later (an hour or so later) learnt that it’s months away (is the 180 days based on how long it’s up for, not 180 days from first install?)

The script can be used as an uptime timer or countdown timer, and an extra feature is that it can log the minutes it’s been up (because I wasn’t totally sure it’s an hour from start to shutdown for expired evals.)

Image: Screenshots of Uptime, Countdown, and slmgr /xpr
Note: In the screenshot above, “minutes to go” is running from a Windows 10 desktop, just wanted to get it all in one image...

The Script

Param([Int]$MinsToHalt,[Int]$WarnMins,[Int]$PadR = 30,[Switch]$Log)

FUNCTION Wr {
  Param([String]$Echo,[String]$Ink = "White",[String]$Back = "DarkMagenta")
  IF(!$Echo){ Write-Host }
  ELSE{ Write-Host $Echo -ForegroundColor $Ink -BackgroundColor $Back -NoNewLine }
}

while($TRUE){
  $GetDate        = Get-Date
  $LastBoot       = (Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
  $MinsRunning    = [Int]($GetDate - $LastBoot).TotalMinutes
  $SecondsRunning = [Int]($GetDate - $LastBoot).TotalSeconds
  If($MinsToHalt -gt 0){
    $GoOrGone = "to go"
    $MinutesToGo = $MinsToHalt - $MinsRunning
    $SecondsToGo = ($MinsToHalt*60) - $SecondsRunning
  } else {
    $GoOrGone = "gone"
    $MinutesToGo = [Int]($GetDate - $LastBoot).TotalMinutes
    $SecondsToGo = [Int]($GetDate - $LastBoot).TotalSeconds
  }
  cls
  If($MinsToHalt -eq 0){ $Ink = "Black"; $Back = "Green" }
  elseif($MinutesToGo -gt $WarnMins){ $Ink = "Black"; $Back = "Green" }
  else{ $Ink = "White"; $Back = "Red" }
  Wr "".PadRight($PadR) $Ink $Back; Wr
  Wr (" Minutes $GoOrGone = " + [String]$MinutesToGo).PadRight($PadR) $Ink $Back; Wr
  Wr (" Seconds $GoOrGone = " + [String]$SecondsToGo).PadRight($PadR) $Ink $Back; Wr
  Wr "".PadRight($PadR) $Ink $Back
  If($Log){ [String]$MinsRunning > "MinsRunning.TXT" }
  sleep 1
}

1 comment:

  1. Thank you for the tips. It really helped a lot. it's really annoying to recover deleted files each time after forgetting data backups.

    ReplyDelete