PowerShell时间记录脚本
#initialization
$timeInterval=30#监测间隔
$record=@{"Coding"=0;"OutlookEmail"=0;"Gmail"=0;"GoogleReader"=0;"BBS"=0;"OtherInternet"=0;"Documents"=0;}
$count=0
$date=date-format"yyyyMMdd"
#trytoresume
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);
}}
}
#starttomonitor
while($true)
{
$titles=ps|?{$_.MainWindowTitle}|selectMainWindowTitle
$titles|%{
if($_-match"Google阅读器-WindowsInternetExplorer"){$record["GoogleReader"]++;}
else{if($_-match"Gmail-WindowsInternetExplorer"){$record["Gmail"]++;}
else{if($_-match"InternetExplorer"){$record["OtherInternet"]++;}
else{if($_-match"VisualStudio"){$record["Coding"]++;}
else{if($_-match"MicrosoftWord"){$record["Documents"]++;}
else{if($_-match"MicrosoftOfficeOneNote"){$record["Documents"]++;}
else{if($_-match"MicrosoftPowerPoint"){$record["Documents"]++;}
else{if($_-match"Message(HTML)"){$record["OutlookEmail"]++;}
else{if($_-match"bbs"){$record["BBS"]++;}
}}}}}}}}
}
sleep($timeInterval)
$count=($count+1)%10#为了防止数据丢失,每10次记录写入文件一次
if($count-eq0){$record>"d:\temp\timeRecord$date.txt"}
}
为了解技术思路,研究了一下powershell.
整个开发与部署过程如下:
1.下载WindowsXP-KB926139-v2-x86-ENU
安装powershell环境;
2.按照代码要求,写一个简单的脚本;
3.运行powershell时,同bat是有区别的.注意以下方法:
1)解除限制:
set-executionpolicyUnrestricted
2)将文件名保存为ps1
3)通过以下方法运行(假如文件名是c:a.ps1)
PSC:>.a
[@more@]
示例代码:
functionfoo([int]$x)
{
$x=$x+1
echo$x
}
foo(1)