欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Powershell小技巧之通过EventLog查看近期电脑开机和关机时间

程序员文章站 2022-09-05 19:18:29
机器开机和关机时写在eventlog中的第一条日志和最后一条日志分别为:6005和6006。 timecreated id leveldisp...

机器开机和关机时写在eventlog中的第一条日志和最后一条日志分别为:6005和6006。

timecreated           id leveldisplayname message
-----------           -- ---------------- -------
8/18/2014 9:23:04 am     6005 information   the event log service was started.  
8/15/2014 7:03:48 pm     6006 information   the event log service was stopped.

所以根据上面的信息很容易得出机器的开机,关机,在线时间,代码为:

function get-computeruptimehistory { 
 $q=' 
<querylist> 
 <query id="0" path="system"> 
  <select path="system">*[system[(eventid=6005 or eventid=6006)]]</select> 
 </query> 
</querylist>'
$events = get-winevent -filterxml $q
$i=-1 
while ( $i+1 -lt $events.length ) { 
 if($i -eq -1) 
 { 
 [pscustomobject]@{ 
 starttime = $events[0].timecreated; 
 stoptime = $null ; 
 uptime = [datetime]::now - $events[0].timecreated 
 } 
 } 
 else{ 
 [pscustomobject]@{ 
 starttime = $events[$i+1].timecreated; 
 stoptime = $events[$i].timecreated ; 
 uptime = $events[$i].timecreated - $events[$i+1].timecreated 
 } 
 } 
 $i += 2 
} 
 
}

输出为:

ps> get-computeruptimehistory | ft -autosize

starttime       stoptime       uptime
---------       --------       ------
8/18/2014 9:23:04 am            2.05:00:22.5891685
8/13/2014 9:30:42 am 8/15/2014 7:03:48 pm 2.09:33:06
7/22/2014 12:16:09 pm 8/13/2014 9:29:09 am 21.21:13:00
7/22/2014 9:23:08 am 7/22/2014 11:26:08 am 02:03:00
7/17/2014 11:08:57 am 7/21/2014 6:20:28 pm 4.07:11:31
7/14/2014 9:35:11 am 7/17/2014 11:07:25 am 3.01:32:14
7/10/2014 3:01:53 pm 7/14/2014 9:21:48 am 3.18:19:55
7/8/2014 5:04:02 pm  7/10/2014 2:58:36 pm 1.21:54:34
6/30/2014 9:17:28 am 7/8/2014 5:01:24 pm  8.07:43:56
6/29/2014 10:24:50 am 6/29/2014 6:04:09 pm 07:39:19
6/20/2014 9:33:08 am 6/27/2014 6:18:34 pm 7.08:45:26
6/16/2014 3:05:45 pm 6/20/2014 9:31:16 am 3.18:25:31
6/12/2014 9:40:05 am 6/16/2014 3:04:02 pm 4.05:23:57
6/6/2014 2:52:11 pm  6/12/2014 9:37:46 am 5.18:45:35
6/5/2014 10:55:20 am 6/6/2014 2:51:09 pm  1.03:55:49
6/5/2014 9:19:38 am  6/5/2014 10:54:04 am 01:34:26
6/3/2014 1:33:24 pm  6/4/2014 7:58:58 pm  1.06:25:34
5/30/2014 10:07:06 am 6/3/2014 1:31:24 pm  4.03:24:18
5/29/2014 5:30:33 pm 5/30/2014 9:41:41 am 16:11:08
5/29/2014 5:28:57 pm 5/29/2014 5:29:43 pm 00:00:46
5/29/2014 2:52:58 pm 5/29/2014 5:26:57 pm 02:33:59
5/29/2014 2:50:31 pm 5/29/2014 2:51:06 pm 00:00:35
5/27/2014 11:54:43 am 5/29/2014 2:47:29 pm 2.02:52:46
5/23/2014 5:31:18 pm 5/26/2014 9:16:33 am 2.15:45:15
5/22/2014 6:00:29 pm 5/23/2014 9:16:45 am 15:16:16
5/21/2014 4:38:22 pm 5/21/2014 4:40:07 pm 00:01:45
5/21/2014 9:43:59 am 5/21/2014 4:36:34 pm 06:52:35
5/19/2014 11:27:28 am 5/21/2014 9:42:32 am 1.22:15:04
5/19/2014 9:25:56 am 5/19/2014 9:27:00 am 00:01:04
5/15/2014 9:23:15 am 5/15/2014 9:24:16 am 00:01:01
5/15/2014 11:18:45 am 5/15/2014 11:19:49 am 00:01:04