Powershell Windows

Powershellを使ったテキストファイルの読み込み

Powershellを用いてテキストファイルを読み込む際に使用するコマンドレットとサンプルスクリプトを解説していきます。

Get-Contentを使ったテキストファイルの読み込み

Powershellでテキストファイルを読み込むには以下のGet-Contentコマンドレットを利用します。

構文

Get-Content -Path {読み込むファイルのパス}

読み込みで使用するsample.txtファイルの中身

//sample.txt
hogehoge
hogehoge2
hogehoge3

使用例

Get-Content -Path "C:\Users\owner\Desktop\sample.txt"

--出力結果--
hogehoge
hogehoge2
hogehoge3

実際はテキストファイルを読み込んで1行ごとに処理を行う場合も多いため、その場合は以下のようにForEach-Objectなどと組み合わせて処理を行います。

Get-Content -Path "C:\Users\owner\Desktop\sample.txt" | ForEach-Object {
    Write-Output $_ //1行ごとにテキストファイルを表示する。
}

--出力結果--
hogehoge
hogehoge2
hogehoge3

Get-Contentのオプション

Get-Contentコマンドレットには様々なオプションがあります。オプションの内一部を以下にまとめておきました。使用例も後述してあります。

オプション名概要
TotalCount先頭から指定した数字の分だけ行数を読み込む
Tail行末から指定した数字の分だけ行数を読み込む
Raw改行を無視し、配列ではなく改行が保持されている1つの文字列としてファイルを取得
Delimiterファイルの中身を配列に分割する際の区切り文字を指定、デフォルト値は\n
ReadCountパイプライン経由で何行の内容を送るかを指定、デフォルト値は1

-TotalCount

Get-Content -Path "C:\Users\owner\Desktop\sample.txt" -TotalCount 2

//出力結果
hogehoge
hogehoge2

-Tail

Get-Content -Path "C:\Users\owner\Desktop\sample.txt" -Tail 2

//出力結果
hogehoge2
hogehoge3

-Raw

$Content = Get-Content -Path "C:\Users\owner\Desktop\sample.txt" -Raw
Write-Output $content.Count //配列の数を表示
$Content2 = Get-Content -Path "C:\Users\owner\Desktop\sample.txt"
Write-Output $content2.Count //配列の数を表示

//出力結果
1
3

-Delimiter

//sample.txt2
hogehoge,hogehoge2,hogehoge3
Get-Content -Path "C:\Users\owner\Desktop\sample2.txt" -Delimiter ","

//出力結果
hogehoge,
hogehoge2,
hogehoge3

-ReadCount

Get-Content "C:\Users\owner\Desktop\sample.txt" -ReadCount 2 | ForEach-Object {
    foreach ($line in $_) {
        Write-Output $line
    }
    Write-Output "----------------"  # 区切りのための行を出力
}

//出力結果
hogehoge
hogehoge2
----------------
hogehoge3
----------------
Get-Content "C:\Users\owner\Desktop\sample.txt" -ReadCount 3 | ForEach-Object {
    foreach ($line in $_) {
        Write-Output $line
    }
    Write-Output "----------------"  # 区切りのための行を出力
}

//出力結果
hogehoge
hogehoge2
hogehoge3
----------------

-Powershell, Windows