LoginSignup
17
33

More than 5 years have passed since last update.

PowerShell を使ってテキストファイル読み込み/書きこみ

Last updated at Posted at 2016-06-29

PowerShell

PowerShellとは
色々細かい処理を作る場合、rubyを使うことが多かったけれど、
標準でWindowsについている機能を使用した方がよい場合があったので乗り換え(乗り換え中)。

コーディング

準備

Windows7 以上であれば標準で PowerShell 2.0 が使用可能。
すべてのプログラム > アクセサリ > Windows PowerShell > Windows PowerShell ISE
というIDEが標準でインストールされている。

テキストファイル読み込み

スクリプトと同じディレクトリにある"test.txt"を読み込んで表示。

# 実行中のパス取得/移動
$path = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $path

# ファイル読み込み
# StreamReaderのコンストラクタに直接 「$path + "\test.txt"」を入力するとエラーになるので分ける
$fileName = $path + "\test.txt"
$file = New-Object System.IO.StreamReader($fileName, [System.Text.Encoding]::GetEncoding("sjis"))
while (($line = $file.ReadLine()) -ne $null)
{
    Write-Host($line)
}
Write-Host("")
$file.Close()

# 終了
Write-Host("終了")

テキストファイル書き込み

スクリプトと同じディレクトリに"test2.txt"を作成して上書き。

# 実行中のパス取得/移動
$path = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $path

# ファイル書きこみ
# StreamReaderのコンストラクタに直接 「$path + "\test.txt"」を入力するとエラーになるので分ける
$fileName = $path + "\test2.txt"
$file = New-Object System.IO.StreamWriter($fileName, $false, [System.Text.Encoding]::GetEncoding("sjis"))
$file.WriteLine("あいうえお")
$file.WriteLine("かきくけこ")
$file.WriteLine("さしすせそ")
Write-Host("")
$file.Close()

# 終了
Write-Host("終了")

参考

https://codezine.jp/article/detail/3592
【改訂新版】 Windows PowerShell ポケットリファレンス

17
33
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
33