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

PowerShell时间记录脚本

程序员文章站 2022-03-14 07:50:28
#initialization $timeinterval = 30 #监测间隔 $record = @{"coding" = 0; "outl...

#initialization
   $timeinterval = 30 #监测间隔
   $record = @{"coding" = 0; "outlook email" = 0; "gmail" = 0; "google reader" = 0; "bbs" = 0; "other internet" = 0; "documents" = 0;}
  $count = 0
  $date = date -format "yyyymmdd"
  #try to resume
  if (test-path "d:\temp\timerecord$date.txt") {
    gc "d:\temp\timerecord$date.txt" | % {if ($_ -match "\w+\s+\d+") {
      $groups = [regex]::match($_, "^(\w+\s?\w+)\s+(\d+)").groups;
      $record[$groups[1].value] = [int]::parse($groups[2].value);
    }}
  }
  #start to monitor
  while ($true)
  {
    $titles = ps | ? {$_.mainwindowtitle} | select mainwindowtitle
    $titles | % {
      if ($_ -match "google 阅读器 - windows internet explorer") {$record["google reader"]++;}
      else {if ($_ -match "gmail - windows internet explorer") {$record["gmail"]++;}
      else {if ($_ -match "internet explorer") {$record["other internet"]++;}
      else {if ($_ -match "visual studio") {$record["coding"]++;}
      else {if ($_ -match "microsoft word") {$record["documents"]++;}
      else {if ($_ -match "microsoft office onenote") {$record["documents"]++;}
      else {if ($_ -match "microsoft powerpoint") {$record["documents"]++;}
      else {if ($_ -match "message (html)") {$record["outlook email"]++;}
      else {if ($_ -match "bbs") {$record["bbs"]++;}
      }}}}}}}}
    }
    sleep($timeinterval)
    $count = ($count + 1) % 10 #为了防止数据丢失,每10次记录写入文件一次
    if ($count -eq 0) {$record > "d:\temp\timerecord$date.txt"}
  }

为了解技术思路,研究了一下powershell.
整个开发与部署过程如下:

1.下载windowsxp-kb926139-v2-x86-enu

安装powershell环境;

2.按照代码要求,写一个简单的脚本;

3. 运行powershell时,同 bat是有区别的.注意以下方法:

1) 解除限制:

set-executionpolicy unrestricted

2) 将文件名保存为ps1
3) 通过以下方法运行(假如文件名是c:a.ps1)
ps c:> .a
[@more@]

示例代码:

function foo ( [int] $x)
{
$x = $x + 1
echo $x
}
foo (1 )