PowerShell で 指定ファイルを読み取るまで
PowerShellバージョン
Version : 5.1.18362.752
目的
- 指定テキストファイルを読み取り、1行ずつ処理する方法を学ぶ。
- 1行ずつ取得したファイルを指定の文字でセパレートし、連想配列のキーとして登録後、カウントをする。
- 調べる過程で興味が沸いたものを取り込んでいく。
作ったサンプルコード
# region Syslogd Log File Analys Tools
##################################################################################
# --------------------------------------------------------------------------------#
#
#
#
#
#
# --------------------------------------------------------------------------------#
# region Prompt Custom
function prompt {
"[Tools]> "
#(Split-Path (Get-Location) -Leaf) + " > "
}
# endregion
# region Clear
Clear-Host
# endregion
# region Path Move
# 現在のパスを取得/格納
$start_path = (Convert-Path .);
Set-Location $start_path;
# 実行中のパス取得/移動
$path = Split-Path -Parent $MyInvocation.MyCommand.Path;
Push-Location $path;
# endregion
# region Input File Path
$infile = "C:\workspace\access_combined_log";
# endregion
# IPベース連想配列を空準備
$ip_table = @{};
# region try-catch!
try {
Write-Host "開始:ファイルをオープンします。" -ForegroundColor Yellow
$fso = New-Object System.IO.StreamReader($infile, [System.Text.Encoding]::GetEncoding("UTF-8"));
while (($line = $fso.ReadLine()) -ne $null) {
# 1行分を空白で分割
$ary_line = $line -split " ";
If($ip_table.ContainsKey($ary_line[0])) {
$ip_table[$ary_line[0]] = $ip_table[$ary_line[0]] + 1;
} else {
$ip_table.Add($ary_line[0],1);
}
}
} catch {
# tryの中でエラーが発生した場合は、ここで処理
$ErrorMessage = $_.Exception_Message
$ErrorMessage
Write-Host "エラー: $error" -ForegroundColor Yellow
} finally {
Write-Host "終了:ファイルをクローズします。" -ForegroundColor Yellow
$fso.Close();
}
# endregion
# region GridDisplay
[String]$row;
foreach ($invalue in $ip_table.Keys) {
$ip_cnt = $ip_table[$invalue];
$row += $invalue + "," + $ip_table[$invalue] + "`n";
}
$row | ConvertFrom-Csv -Header @("IP-Addr","Count")| Out-GridView -Title "IP Base Counter"
Remove-Variable row
# endregion
# region
Pop-Location;
# endregion
# endregion
# EOF
まとめ
連想配列の定義場所
最初は、try
文の中で定義してしまっていたので、連想配列が最後の一つだけしか登録されていなかった。
プロンプト表示
プロンプト表示は変更出来る。
カレントディレクトリの操作
スクリプトが格納されている場所に移動ができる。
pushとpopで戻れる。便利。
Set-Location
もよいけれど、個人的にはpush
やpop
が感じよかった。
Out-GridViewの出力情報
最初、$row
変数を初期化しないで利用していたら、どんどん前のレコードが残ったまま表示されていた。
なので、Remove-Variable
で削除する。削除する時は、$
を付けない。