PowerShellでテキストファイルを操作するコマンドレット

コンピュータ

テキストファイルを扱うコマンドレットをまとめて見ました。

ファイルの作成

New-Item -ItemType File -Path "C:\path\to\file.txt" -Force | Out-Null

-Force を付けると、すでに存在していてもエラーにならず、上書きはされません

エイリアス:

Get-Alias -Definition New-Item

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ni -> New-Item

読み込み

Get-Content "C:\path\to\file.txt"

エイリアス:

Get-Alias -Definition Get-Content

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           cat -> Get-Content
Alias           gc -> Get-Content
Alias           type -> Get-Content

書き込み

Set-Content "C:\path\to\file.txt" "Hello, world!"

エイリアス:なし

追記

Add-Content "C:\path\to\file.txt" "追記の内容"

末尾に改行後追加されます。

エイリアス:

Get-Alias -Definition Add-Content

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           ac -> Add-Content

パイプラインの出力先をファイルにする

"出力内容" | Out-File "C:\path\to\file.txt" -Encoding UTF8

検索

ファイル内の文字列を検索

Select-String -Path "C:\path\to\file.txt" -Pattern "キーワード"

エイリアス:

Get-Alias -Definition Select-String

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           sls -> Select-String

1行毎処理を行う

読み込み~処理~書き出し

Get-Content "input.txt" | ForEach-Object { $_.ToUpper() } | Set-Content "output.txt"

エイリアス:

Get-Alias -Definition ForEach-Object

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           foreach -> ForEach-Object

コメント