LoginSignup
0
1

More than 3 years have passed since last update.

PowerShell で 指定ファイルを読み取るまで

Posted at

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もよいけれど、個人的にはpushpopが感じよかった。

Out-GridViewの出力情報

最初、$row変数を初期化しないで利用していたら、どんどん前のレコードが残ったまま表示されていた。
なので、Remove-Variableで削除する。削除する時は、$を付けない。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1