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-Volumeコマンドレットの使い方

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

no image

PowerShellでCSVファイルを出力する

こんにちは、今日はPowerShellでCSVファイルを出力する方法についてまとめていきます。 確認環境 PSVersion 5.1.18362.1110 CSVファイルを出力する CSVファイルを出 …

no image

PowerShellでクリップボードの値の取得と設定をする方法

取得 Get-Clipboard ファイルを選択している場合 Get-Clipboard -Format FileDropList 設定 Set-Clipboard 設定したい値 設定はClipでも可 …

no image

PowerShellで実行ポリシーを取得するコマンドレットGet-ExecutionPolicyの使い方

こんにちは、今日はPowerShellで実行ポリシーを取得するコマンドレットGet-ExecutionPolicyの使い方についてまとめていきます。 確認環境 PSVersion 5.1.18362. …

no image

PowerShellでディレクトリを移動するコマンドレットSet-Locationの使い方

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