📂

PowerShellで始めるファイル操作の基本テクニック

に公開

PowerShellで始めるファイル操作の基本テクニック

PowerShellはWindowsに標準搭載されている強力なシェルであり、ファイル操作も直感的に行えます。この記事では、PowerShellを使った基本的なファイル操作について解説します。

PowerShellとは?

PowerShellは、Windowsのコマンドプロンプトよりも高度な機能を持つコマンドラインインターフェースです。オブジェクト指向であり、多くのコマンドレット(cmdlet)が用意されています。

基本的なファイル操作コマンド

1. ファイルの一覧表示 (Get-ChildItem)

# カレントディレクトリのファイル一覧を表示
Get-ChildItem

# 省略形で使用
ls
dir

特定のパターンのファイルだけを表示することも簡単です。

# .txtファイルのみ表示
Get-ChildItem -Filter *.txt

# サブディレクトリも含めて検索
Get-ChildItem -Recurse -Filter *.jpg

2. ファイルの作成 (New-Item)

# 空のテキストファイルを作成
New-Item -Path "test.txt" -ItemType "file"

# 内容を指定して作成
New-Item -Path "hello.txt" -ItemType "file" -Value "Hello, PowerShell!"

3. ファイルの読み取り (Get-Content)

# ファイルの内容を表示
Get-Content -Path "test.txt"

# 省略形
cat test.txt

# 最初の5行だけ表示
Get-Content -Path "log.txt" -TotalCount 5

# 最後の10行を表示
Get-Content -Path "log.txt" -Tail 10

4. ファイルへの書き込み

# ファイルに内容を書き込む(上書き)
"Hello World" | Out-File -FilePath "output.txt"

# ファイルに追記する
"Additional line" | Add-Content -Path "output.txt"

5. ファイルのコピー (Copy-Item)

# ファイルをコピー
Copy-Item -Path "source.txt" -Destination "destination.txt"

# ディレクトリごとコピー(再帰的)
Copy-Item -Path "SourceFolder" -Destination "DestFolder" -Recurse

6. ファイル/ディレクトリの移動 (Move-Item)

# ファイルの移動
Move-Item -Path "file.txt" -Destination "NewFolder/"

# ファイル名の変更も同じコマンド
Move-Item -Path "oldname.txt" -Destination "newname.txt"

7. ファイル/ディレクトリの削除 (Remove-Item)

# ファイルの削除
Remove-Item -Path "unnecessary.txt"

# 確認プロンプトなしで削除
Remove-Item -Path "temp.txt" -Force

# ディレクトリを再帰的に削除
Remove-Item -Path "OldFolder" -Recurse

応用テクニック

ファイルの検索と処理の組み合わせ

# 特定のテキストを含むファイルを検索
Get-ChildItem -Recurse -Filter *.txt | Select-String -Pattern "検索ワード"

# 一週間以上前のログファイルを削除
Get-ChildItem -Path "logs" -Filter *.log | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | 
    Remove-Item

ファイル属性の変更

# ファイルを読み取り専用に設定
Set-ItemProperty -Path "important.txt" -Name IsReadOnly -Value $true

# ファイル属性の確認
Get-ItemProperty -Path "important.txt" | Select-Object IsReadOnly

CSVファイルの処理

PowerShellはCSVファイルの処理も得意です。

# CSVファイルの読み込み
$data = Import-Csv -Path "data.csv"

# データを処理
$data | ForEach-Object {
    $_.Name = $_.Name.ToUpper()
}

# 処理したデータを新しいCSVとして保存
$data | Export-Csv -Path "processed.csv" -NoTypeInformation

まとめ

PowerShellを使うことで、ファイル操作を効率的に行うことができます。コマンドプロンプトより直感的で、バッチ処理も簡単に実装できます。また、PowerShellの特徴であるパイプライン処理を活用すれば、複雑なファイル操作も簡潔に記述できます。

PowerShellの基本的なファイル操作を覚えておくと、日常的なファイル管理作業が格段に効率化されるでしょう。まずは簡単なコマンドから試して、PowerShellの便利さを体験してみてください。

Discussion