3テラバイト

プログラム関連備忘録サイト。主にゲーム。

PowerShell

PowerShellでテキストファイルを1行ずつ処理する

投稿日:

こんにちは、今日はPowerShellでテキストファイルを1行ずつ処理する方法についてまとめていきます。

確認環境

PSVersion 5.1.18362.1110

テキストファイルを1行ずつ処理する

Get-Contentコマンドレットでテキストファイルの内容を取得する方法、System.IO.StreamReaderオブジェクトを使用する方法の2通りの方法を記載します。

Get-Content

$fileName = "test.txt"
$file = (Get-Content -Encoding utf8 $fileName) -as [string[]]
foreach ($line in $file) {
    Write-Host $line
}

System.IO.StreamReader

$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

-PowerShell


comment

メールアドレスが公開されることはありません。

関連記事

no image

PowerShellでアイテムのコンテンツを取得するコマンドレットGet-Contentの使い方

こんにちは、今日はPowerShellでアイテムのコンテンツを取得するコマンドレットGet-Contentの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 …

no image

PowerShellで右寄せ左寄せする方法

こんにちは、今日はPowerShellで右寄せ左寄せする方法についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 右寄せ "{0,5}" -f 1 …

no image

PowerShellの比較演算子一覧

確認環境 PSVersion 5.1.18362.1110 比較演算子 演算子他言語の演算子説明-eq==等しい(equal)-ne!=等しくない(not equal)-gt>より大きい(Greate …

no image

PowerShellでロード済のアセンブリ一覧を取得する

以下のように現在のアプリケーション ドメインを取得し、そのドメインで読み込まれているアセンブリをGetAssemblies関数で取得します。 PS C:\Users\santerabyte> & …

no image

PowerShellでWindows Management Instrumentation (WMI)オブジェクトを取得するコマンドレットGet-WmiObjectの使い方

こんにちは、今日はPowerShellでWindows Management Instrumentation (WMI)オブジェクトを取得するコマンドレットGet-WmiObjectの使い方についてま …