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
CommandType : Alias
Definition : Get-WmiObject
ReferencedCommand : Get-WmiObject
ResolvedCommand : Get-WmiObject
Get-Alias | Where{$_.Definition -eq "Get-Member"} | FL
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.
- # ======================================
- # Script Name: SystemUptime.PS1
- # Storage Path: D:\PowerShell\
- # Author: Jason A.Yoder, MCT
- # Company: MCTExpert, Inc.
- # Website: www.MCTExpert.com
- # Blog: www.MCTExpert.blogspot.com
- # Version: 1.0
- # Created: September 4, 2009
- # Purpose: To be able to calculate the
- # current system uptime.
- # ======================================
- # ======================================
- # Variables
- # --------------------------------------
- # Set debug level to strict
- Set-PSDebug -strict
- # Name: $Current_Time
- # Purpose: Holds the current Date and
- # time information from the
- # local client.
- $Current_Time
- # Name: $strOSBootTime
- # Purpose: Holds the string value of the
- # boot time for the operating
- # operating system.
- $strOSBootTime = ""
- # Name: $UpTime
- # Purpose: Object holds the Date/Time
- # difference information
- $UpTime = ""
- # ======================================
- # ======================================
- # Version History
- # --------------------------------------
- # Version:
- # Date:
- # Reason:
- # ======================================
- # ======================================
- # Functions
- # --------------------------------------
- #
- Function Get-CurrentDateTime
- {
- # Function: Get-CurrentDateTime
- # Arguments: None
- # Purpose: Returns the current DateTime
- # object to the variable
- # $Current_Time
- $Current_Time = Get-Date
- }
- # --------------------------------------
- Function Get-BootString
- {
- # Function: GetBootString
- # Arguments: None
- # Purpose: Returns a string of the
- # Date/Time the local computer
- # was booted on.
- # --------------------------------------
- $strOSBootTime=Get-WmiObject win32_operatingSystem
- $Script:strOSBootTime=[Management.ManagementDateTimeConverter]::ToDateTime($strOSBootTime.LastBootUpTime)
- }
- # --------------------------------------
- Function Show-Uptime
- {
- # Function: Show-Uptime
- # Arguments:
- # - $Current : The current system time.
- # - $Boot : The boot time.
- # Purpose:
- # --------------------------------------
- $Script:UpTime = $Current_Time.subtract($strOSBootTime)
- }
- # --------------------------------------
- Function Show-Data
- {
- # Function: Show-Data
- # Arguments: None
- # Purpose: Displays the information
- # stored in object $UpTime
- # in a user friendly way.
- # --------------------------------------
- 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"
- }
- # ======================================
- # End of Functions
- # ======================================
- # ======================================
- # Script Body
- # --------------------------------------
- Get-CurrentDateTime(0)
- Get-BootString(0)
- Show-Uptime(0)
- Show-Data(0)
- # ======================================
- # Script Body
- # ======================================
- Get-CurrentDateTime(0)
- Get-BootString(0)
- Show-Uptime(0)
- Show-Data(0)
- # ======================================
- # End of Script Body
- # ======================================
· 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"
Comments