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

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


reCaptcha の認証期間が終了しました。ページを再読み込みしてください。

関連記事

no image

PowerShellでプロセスを取得するコマンドレットGet-Processの使い方

こんにちは、今日はPowerShellでプロセスを取得するコマンドレットGet-Processの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 Get-P …

no image

PowerShellでコマンド一覧を取得するコマンドレットGet-Commandの使い方

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

no image

PowerShellでボリューム情報を取得するGet-Volumeコマンドレットの使い方

こんにちは、今日はPowerShellでボリューム情報を取得するGet-Volumeコマンドレットの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 Vol …

no image

PowerShellでアイテムをコピーするコマンドレットCopy-Itemの使い方

こんにちは、今日はPowerShellでアイテムをコピーするコマンドレットCopy-Itemの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 パラメータ …

no image

PowerShellで現在のディレクトリを表示するコマンドレットGet-Locationの使い方

こんにちは、今日はPowerShellで現在のディレクトリを表示するコマンドレットGet-Locationの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 …