こんにちは、今日はPowerShellでテキストファイルを1行ずつ処理する方法についてまとめていきます。
Table of Contents
確認環境
PSVersion 5.1.18362.1110
テキストファイルを1行ずつ処理する
Get-Contentコマンドレットでテキストファイルの内容を取得する方法、System.IO.StreamReaderオブジェクトを使用する方法の2通りの方法を記載します。
Get-Content
1 2 3 4 5 | $fileName = "test.txt" $file = ( Get-Content -Encoding utf8 $fileName ) -as [string[]] foreach ( $line in $file ) { Write-Host $line } |
System.IO.StreamReader
1 2 3 4 5 6 7 | $fileName = "test.txt" $file = New-Object System.IO.StreamReader( $fileName , [System.Text.Encoding] ::GetEncoding( "utf-8" )) while (( $line = $file .ReadLine()) -ne $null ) { Write-Host $line } $file .Close() |
リンク
Get-Content (Microsoft.PowerShell.Management) – PowerShell | Microsoft Docs
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-7.1