1. ホーム
  2. スクリプト・コラム
  3. パワーシェル

PowerShellタイムロギングスクリプト

2022-01-05 03:24:50

#initialization
   $timeInterval = 30 #monitoring interval
   $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 Reader - 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 # To prevent data loss, write to the file once every 10 records
    if ($count -eq 0) {$record > "d:\temp\timeRecord$date.txt"}
  }


技術的な考え方を理解するために、powershellについて調べました。
開発・展開の全体の流れは以下の通りです。

1. Download WindowsXP-KB926139-v2-x86-ENU

powershell 環境をインストールします。

2. コードの要件に従って、簡単なスクリプトを書く。

3. powershellを実行する場合、batとの違いがあります。以下の方法に注意してください。

1)アンリストラクト

set-executionpolicy Unrestricted

2) ファイル名を ps1 として保存します。
3) 実行(ファイル名が c:a.ps1 の場合)スルー
PS C:> .a
[もっと見る]

コード例です。

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