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で関数を定義する方法

定義方法 引数なし 引数なしの関数は以下のように定義します。中かっこの中に任意の処理を記述します。 function Test-Func { Write-Host Hello World } 実行する …

no image

PowerShellでアイテムのプロパティを取得するコマンドレットGet-ItemPropertyの使い方

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

no image

PowerShellで現在の日時を取得するコマンドレットGet-Dateの使い方

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

no image

PowerShellで特定ディレクトリのファイル内文字列を置換する

Get-ChildItem . | ForEach-Object {Get-Content -Encoding utf8 $_ | ForEach-Object {$_ -creplace &#039 …

no image

PowerShellで文字列が特定の文字列から始まっているか判定する

確認環境 PSVersion 5.1.18362.1110 特定の文字から始まっているか判定 stringのStartsWith関数に文字列を渡すと、その文字列で始まっているか判定することができます。 …