Wednesday, December 3, 2014

#34 : Find uptime of the host using Powershell

Sometimes we need to know the uptime of a host while troubleshooting. It plays lot more important role while troubleshooting.

We can use net stats srv command to get this information. If you check the output of this command, you will see a line which shows uptime is "Statistics since .. ". You can use this line and get desired result by doing some pipelining. The result should compare from current time and give result in number of days,hours, minutes and seconds.

You can see the article about "Difference between two dates" here for better understanding.

Let's try the command "net stats srv"

net stats srv 

Server Statistics for \\WIN-4SV8KNP9VNV


Statistics since 7/16/2017 1:11:09 AM


Sessions accepted                  0
Sessions timed-out                 0
Sessions errored-out               0

Kilobytes sent                     0
Kilobytes received                 0

Mean response time (msec)          0

System errors                      0
Permission violations              0
Password violations                0

Files accessed                     0
Communication devices accessed     0
Print jobs spooled                 0

Times buffers exhausted

  Big buffers                      0
  Request buffers                  0

The command completed successfully.



You may  notice that we can remove "Statistics since" and then uptime is there to be processed. We will use the same logic.


clear 
$uptime=net stats srv | where {$_ -match "since"} | foreach {$_.replace("Statistics since","") } | 
foreach { $($((Get-Date) - (Get-Date $_)).Days).tostring().padleft(3,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Hours).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Minutes).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Seconds).tostring().padleft(2,"0").tostring() 
 } | foreach { $_.replace(" ", "") } 

echo "Uptime of Host [$(hostname)]`t: $uptime (DD:HH:MM:SS)"


Output:
Uptime of Host [Divine] : 000:00:45:24 (DD:HH:MM:SS)

The above script can be modified to generate a report based on all hosts in your environment. But, I would like you to at least comment once. How long I would write without any comment?

2 comments:

  1. Nice! I will be trying this out tomorrow. I need to find a way to alert my users when their devices have not been restarted in >8 days. Thanks!

    ReplyDelete

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...