powershell でファイル読み書き

最近、必要に迫られてちょくちょく触る powershell。とりあえず、ファイル読み書きサンプルを自分用にメモしておきます。

■ FileReadWrite.ps1

$input = "C:\Users\test\Desktop\powershell\input.txt"
$output1 = "C:\Users\test\Desktop\powershell\output1.txt"
$output2 = "C:\Users\test\Desktop\powershell\output2.txt"

Write-Host "-----read write line-----"
$sr = New-Object System.IO.StreamReader($input)
$sw = New-Object System.IO.StreamWriter($output1)
$line
while(($line = $sr.ReadLine()) -ne $null) {
  Write-Host $line
  $sw.WriteLine($line.ToUpper())
}
$sw.Close()
$sr.Close()

Write-Host "-----read character-----"
$sr = New-Object System.IO.StreamReader($input)
while($sr.Peek() -ge 0) {
  $c = [int]$sr.Read()
  if($c -ne 13) {
    Write-Host $c -noNewLine
  } else {
    Write-Host $c -noNewLine
    $c = $sr.Read()
    Write-Host $c
  }
}
Write-Host ""
$sr.Close()

Write-Host "-----Get-Conetnt Out-File-----"
Get-Content $input
Get-Content $input | Out-File $output2 -Encoding default

■ 出力結果

-----read write line-----
aaaaa
bbbbb
ccccc
ddddd
eeeee
-----read character-----
97979797971310
98989898981310
99999999991310
1001001001001001310
101101101101101
-----Get-Conetnt Out-File-----
aaaaa
bbbbb
ccccc
ddddd
eeeee

■ output1.txt

AAAAA
BBBBB
CCCCC
DDDDD
EEEEE

■ output2.txt

aaaaa
bbbbb
ccccc
ddddd
eeeee

なんか簡単なツールでもいいから作ってみたいですね。

[ 環境情報 ]
Windows 10
powershell 5.0