Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Tuesday, September 29, 2009

Calculating Your System Uptime in PowerShell

Today’s PowerShell lesson is on how to determine your system uptime. I know, not very sexy. It will introduce us to some date/time math though.


Before we begin, I just want to clearify the text formatting that I'm using:

This means it is something that I typed.

This is the resulting output.

When We get to the actual scripts, I'll color code the comments out so you can focus on the code.

The first thing that I want to do is discover how to get the current date and time from my client in PowerShell.

Get-Date

Friday, September 04, 2009 3:05:43 PM

Easy enough. You can see that Windows will format the output as DayOfWeek, Month Day, Year Hour:Minute:Second Am/PM. OK, so we know what time it is now. But when did your computer turn on last? We are going to pull this information from the WMI class of Win32_Operating System. Let’s take a look at the properties of this class.

Gwmi Win32_OperatingSystem | gm

In the above command, GWIM is an alias for Get-WmiObject and GM is an alias for Get-Member. Don’t believe me? Try these commands.

Get-Alias | Where{$_.Definition -eq "Get-WmiObject"} | FL

Name : gwmi

CommandType : Alias

Definition : Get-WmiObject

ReferencedCommand : Get-WmiObject

ResolvedCommand : Get-WmiObject

Get-Alias | Where{$_.Definition -eq "Get-Member"} | FL

Name : gm

CommandType : Alias

Definition : Get-Member

ReferencedCommand : Get-Member

ResolvedCommand : Get-Member

OK, back to the task at hand. Execute the command below

gwmi Win32_OperatingSYstem | gm -membertype property

TypeName: System.Management.ManagementObject#root\cimv2\Win32_OperatingSystem

Name MemberType Definition

---- ---------- ----------

BootDevice Property System.String BootDevice {get;set;}

BuildNumber Property System.String BuildNumber {get;set;}

BuildType Property System.String BuildType {get;set;}

Caption Property System.String Caption {get;set;}

CodeSet Property System.String CodeSet {get;set;}

CountryCode Property System.String CountryCode {get;set;}

CreationClassName Property System.String CreationClassName {get;set;}

CSCreationClassName Property System.String CSCreationClassName {get;set;}

CSDVersion Property System.String CSDVersion {get;set;}

CSName Property System.String CSName {get;set;}

CurrentTimeZone Property System.Int16 CurrentTimeZone {get;set;}

DataExecutionPrevention_32BitApplications Property System.Boolean DataExecutionPrevention_32BitApplications {get;set;}

DataExecutionPrevention_Available Property System.Boolean DataExecutionPrevention_Available {get;set;}

DataExecutionPrevention_Drivers Property System.Boolean DataExecutionPrevention_Drivers {get;set;}

DataExecutionPrevention_SupportPolicy Property System.Byte DataExecutionPrevention_SupportPolicy {get;set;}

Debug Property System.Boolean Debug {get;set;}

Description Property System.String Description {get;set;}

Distributed Property System.Boolean Distributed {get;set;}

EncryptionLevel Property System.UInt32 EncryptionLevel {get;set;}

ForegroundApplicationBoost Property System.Byte ForegroundApplicationBoost {get;set;}

FreePhysicalMemory Property System.UInt64 FreePhysicalMemory {get;set;}

FreeSpaceInPagingFiles Property System.UInt64 FreeSpaceInPagingFiles {get;set;}

FreeVirtualMemory Property System.UInt64 FreeVirtualMemory {get;set;}

InstallDate Property System.String InstallDate {get;set;}

LargeSystemCache Property System.UInt32 LargeSystemCache {get;set;}

LastBootUpTime Property System.String LastBootUpTime {get;set;}

LocalDateTime Property System.String LocalDateTime {get;set;}

Locale Property System.String Locale {get;set;}

Manufacturer Property System.String Manufacturer {get;set;}

MaxNumberOfProcesses Property System.UInt32 MaxNumberOfProcesses {get;set;}

MaxProcessMemorySize Property System.UInt64 MaxProcessMemorySize {get;set;}

MUILanguages Property System.String[] MUILanguages {get;set;}

Name Property System.String Name {get;set;}

NumberOfLicensedUsers Property System.UInt32 NumberOfLicensedUsers {get;set;}

NumberOfProcesses Property System.UInt32 NumberOfProcesses {get;set;}

NumberOfUsers Property System.UInt32 NumberOfUsers {get;set;}

OperatingSystemSKU Property System.UInt32 OperatingSystemSKU {get;set;}

Organization Property System.String Organization {get;set;}

OSArchitecture Property System.String OSArchitecture {get;set;}

OSLanguage Property System.UInt32 OSLanguage {get;set;}

OSProductSuite Property System.UInt32 OSProductSuite {get;set;}

OSType Property System.UInt16 OSType {get;set;}

OtherTypeDescription Property System.String OtherTypeDescription {get;set;}

PAEEnabled Property System.Boolean PAEEnabled {get;set;}

PlusProductID Property System.String PlusProductID {get;set;}

PlusVersionNumber Property System.String PlusVersionNumber {get;set;}

Primary Property System.Boolean Primary {get;set;}

ProductType Property System.UInt32 ProductType {get;set;}

QuantumLength Property System.Byte QuantumLength {get;set;}

QuantumType Property System.Byte QuantumType {get;set;}

RegisteredUser Property System.String RegisteredUser {get;set;}

SerialNumber Property System.String SerialNumber {get;set;}

ServicePackMajorVersion Property System.UInt16 ServicePackMajorVersion {get;set;}

ServicePackMinorVersion Property System.UInt16 ServicePackMinorVersion {get;set;}

SizeStoredInPagingFiles Property System.UInt64 SizeStoredInPagingFiles {get;set;}

Status Property System.String Status {get;set;}

SuiteMask Property System.UInt32 SuiteMask {get;set;}

SystemDevice Property System.String SystemDevice {get;set;}

SystemDirectory Property System.String SystemDirectory {get;set;}

SystemDrive Property System.String SystemDrive {get;set;}

TotalSwapSpaceSize Property System.UInt64 TotalSwapSpaceSize {get;set;}

TotalVirtualMemorySize Property System.UInt64 TotalVirtualMemorySize {get;set;}

TotalVisibleMemorySize Property System.UInt64 TotalVisibleMemorySize {get;set;}

Version Property System.String Version {get;set;}

WindowsDirectory Property System.String WindowsDirectory {get;set;}

__CLASS Property System.String __CLASS {get;set;}

__DERIVATION Property System.String[] __DERIVATION {get;set;}

__DYNASTY Property System.String __DYNASTY {get;set;}

__GENUS Property System.Int32 __GENUS {get;set;}

__NAMESPACE Property System.String __NAMESPACE {get;set;}

__PATH Property System.String __PATH {get;set;}

__PROPERTY_COUNT Property System.Int32 __PROPERTY_COUNT {get;set;}

__RELPATH Property System.String __RELPATH {get;set;}

__SERVER Property System.String __SERVER {get;set;}

__SUPERCLASS Property System.String __SUPERCLASS {get;set;}

Not very pretty is it. We are interested in the property LastBootUpTime. Let’s take a closer look at this property. First off, create a variable to hol this object

$osBootTime=Get-WmiObject win32_operatingSystem

Now type:

$OSBootTime.LastBootUpTime

20090904112452.262406-240

Yes, this is actually how Windows reads date/time information. We need to make this more user friendly. Try this command to make things look a bit nicer

[Management.ManagementDateTimeConverter]::ToDateTime($OSBootTime.LastBootUpTime)

Friday, September 04, 2009 11:24:52 AM

OK, now we need to figure out the time difference between the current date/time and the string of text that was returned from the previous command. Now it is time for things to get interesting. We will use the Subtract method that is part of each System.DateTime object. Let’s take a look at the code.

For those of you who know me, I like to keep my Main code as simple as possible. That means we are going to be creating a lot of functions and just using the main script code for traffic control. Anything in green are comments.

  1. # ======================================
  2. # Script Name: SystemUptime.PS1
  3. # Storage Path: D:\PowerShell\
  4. # Author: Jason A.Yoder, MCT
  5. # Company: MCTExpert, Inc.
  6. # Website: www.MCTExpert.com
  7. # Blog: www.MCTExpert.blogspot.com
  8. # Version: 1.0
  9. # Created: September 4, 2009
  10. # Purpose: To be able to calculate the
  11. # current system uptime.
  12. # ======================================
  13. # ======================================
  14. # Variables
  15. # --------------------------------------
  16. # Set debug level to strict
  17. Set-PSDebug -strict
  18. # Name: $Current_Time
  19. # Purpose: Holds the current Date and
  20. # time information from the
  21. # local client.
  22. $Current_Time
  23. # Name: $strOSBootTime
  24. # Purpose: Holds the string value of the
  25. # boot time for the operating
  26. # operating system.
  27. $strOSBootTime = ""
  28. # Name: $UpTime
  29. # Purpose: Object holds the Date/Time
  30. # difference information
  31. $UpTime = ""
  32. # ======================================
  33. # ======================================
  34. # Version History
  35. # --------------------------------------
  36. # Version:
  37. # Date:
  38. # Reason:
  39. # ======================================
  40. # ======================================
  41. # Functions
  42. # --------------------------------------
  43. #
  44. Function Get-CurrentDateTime
  45. {
  46. # Function: Get-CurrentDateTime
  47. # Arguments: None
  48. # Purpose: Returns the current DateTime
  49. # object to the variable
  50. # $Current_Time
  51. $Current_Time = Get-Date
  52. }
  53. # --------------------------------------
  54. Function Get-BootString
  55. {
  56. # Function: GetBootString
  57. # Arguments: None
  58. # Purpose: Returns a string of the
  59. # Date/Time the local computer
  60. # was booted on.
  61. # --------------------------------------
  62. $strOSBootTime=Get-WmiObject win32_operatingSystem
  63. $Script:strOSBootTime=[Management.ManagementDateTimeConverter]::ToDateTime($strOSBootTime.LastBootUpTime)
  64. }
  65. # --------------------------------------
  66. Function Show-Uptime
  67. {
  68. # Function: Show-Uptime
  69. # Arguments:
  70. # - $Current : The current system time.
  71. # - $Boot : The boot time.
  72. # Purpose:
  73. # --------------------------------------
  74. $Script:UpTime = $Current_Time.subtract($strOSBootTime)
  75. }
  76. # --------------------------------------
  77. Function Show-Data
  78. {
  79. # Function: Show-Data
  80. # Arguments: None
  81. # Purpose: Displays the information
  82. # stored in object $UpTime
  83. # in a user friendly way.
  84. # --------------------------------------
  85. Write-Host "Your System has been up for:"
  86. Write-Host $UpTime.Days + " Days"
  87. Write-Host $UpTime.Hours + " Hours"
  88. Write-Host $UpTime.Minutes + " Minutes"
  89. Write-Host $UpTime.Seconds + " Seconds"
  90. }
  91. # ======================================
  92. # End of Functions
  93. # ======================================
  94. # ======================================
  95. # Script Body
  96. # --------------------------------------
  97. Get-CurrentDateTime(0)
  98. Get-BootString(0)
  99. Show-Uptime(0)
  100. Show-Data(0)
  101. # ======================================
  102. # Script Body
  103. # ======================================
  104. Get-CurrentDateTime(0)
  105. Get-BootString(0)
  106. Show-Uptime(0)
  107. Show-Data(0)
  108. # ======================================
  109. # End of Script Body
  110. # ======================================

· Lines 1 – 12

o Just my header information.

· Lines 14-37

o This is where I’m declaring my variables up front.

o The command Set-PSDebug –Strict I like using the VBScript command of Option Explicit.

· Lines 40-46

o This section is used to keep track of versions and changes.

· Lines 55-65

o In this function, we are simply settings the current DateTime object into a variable.

· Lines 70-82

o We are calling the boot time of the system and placing it into a variable

o We are also converting it into a usable format.

· Lines 87-98

o Here is were the difference between the dates and time are calculated.

· Lines 102-116

o This functions displays the data in a user friendly way.

· Lines 125-135

o This is the main script body.

Did I need to write so much code to do this? No I did not. I wrote this code in a way to help others understand what I did and to also remind myself in the future how I did it. Below is the code in the shortest format that I know how to write it in.

$Current_Time = Get-Date

$strOSBootTime=Get-WmiObject win32_operatingSystem

$Script:strOSBootTime=[Management.ManagementDateTimeConverter]::ToDateTime($strOSBootTime.LastBootUpTime)

$Script:UpTime = $Current_Time.subtract($strOSBootTime)

Write-Host "Your System has been up for:"

Write-Host $UpTime.Days + " Days"

Write-Host $UpTime.Hours + " Hours"

Write-Host $UpTime.Minutes + " Minutes"

Write-Host $UpTime.Seconds + " Seconds"

No comments: