PowerShell 実践応用
PowerShell は単なるターミナルツールではなく、Windows 環境で最も機能が充実した自動化プラットフォームの一つです。
このセクションでは3 つの主要な実践応用シナリオを通じて、PowerShell の日常管理、リモート運用、技術横断的統合における強力な機能を紹介します:
- 日常管理タスクの自動化
- リモート管理
- 他技術との統合
一、日常管理タスクの自動化
1.1 ファイルの一括リネーム
要件:
ディレクトリ内のすべての.txtファイルを統一プレフィックス+連番の形式にリネームします。例:log_001.txt、log_002.txtなど。
サンプルコード:
$files = Get-ChildItem -Path "D:\Logs" -Filter "*.txt"
$count = 1
foreach ($file in $files) {
$newName = "log_{0:D3}.txt" -f $count
Rename-Item -Path $file.FullName -NewName $newName
$count++
}
一時ファイルの定期削除
例:7 日前より前の一時ファイルを削除
$targetPath = "C:\Windows\Temp"
Get-ChildItem -Path $targetPath -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
Remove-Item -Force -Recurse
スクリプトを.ps1ファイルとして保存し、タスクスケジューラ(Task Scheduler)を使用して定期的に実行することをお勧めします。
システム情報収集スクリプト
$info = [PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption
Uptime = ((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToString()
CPU = (Get-CimInstance Win32_Processor).Name
RAM_GB = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)
}
$info | Format-List
ログ分析とレポート生成
$logPath = "C:\inetpub\logs\LogFiles\W3SVC1\*.log"
$lines = Get-Content $logPath | Where-Object { $_ -match "500" }
$lines.Count
$lines | Out-File "C:\Reports\error_500_report.txt"
二、リモート管理
PowerShell Remoting の基礎
PowerShell Remoting は、WinRM を介してリモートコマンド実行を実現する仕組みです。
リモート機能を有効にする(管理者として実行):
Enable-PSRemoting -Force
使用Invoke-Commandリモートコマンドの実行
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name "W32Time"
}
複数のホストでの一括実行に対応:
$servers = @("Server01", "Server02")
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-Process | Where-Object { $_.CPU -gt 100 }
}
リモートセッション管理
セッションの作成:
$session = New-PSSession -ComputerName "Server01"
セッションへの接続:
Enter-PSSession $session
コマンドの実行:
Invoke-Command -Session $session -ScriptBlock { Get-Date }
セッションの終了:
Remove-PSSession $session
セキュリティ上の考慮事項
- HTTP ではなく HTTPS を使用する(証明書を構成)
- 平文パスワードの使用を避け、資格情報オブジェクトの使用を推奨します:
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock { hostname }
三、他技術との統合
PowerShell と .NET Framework
PowerShell には .NET クラスライブラリへのアクセス機能が組み込まれており、ほぼすべての .NET API を呼び出すことができます。
例:ファイルの MD5 値を取得
function Get-FileHashMD5 {
param ([string]$path)
$md5 = [System.Security.Cryptography.MD5]::Create()
$bytes = [System.IO.File]::ReadAllBytes($path)
$hash = $md5.ComputeHash($bytes)
return ([BitConverter]::ToString($hash)).Replace("-", "")
}
Get-FileHashMD5 "D:\file.zip"
REST API の呼び出し
例:JSON API を呼び出して天気情報を取得
$response = Invoke-RestMethod -Uri "https://api.weatherapi.com/v1/current.json?key=APIKEY&q=Beijing" $response.location.name $response.current.temp_c
データベース接続の基礎(SQL Server を例として)
$connectionString = "Server=localhost;Database=TestDB;Integrated Security=True"
$query = "SELECT TOP 10 * FROM Users"
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
$connection.Open()
$reader = $command.ExecuteReader()
while ($reader.Read()) {
Write-Output $reader["UserName"]
}
$connection.Close()
Office アプリケーションとの連携
例:Excel COM オブジェクトを使用してデータを書き込む
$excel = New-Object -ComObject Excel.Application $excel.Visible = $true $workbook = $excel.Workbooks.Add() $sheet = $workbook.Worksheets.Item(1) $sheet.Cells.Item(1, 1) = "Name" $sheet.Cells.Item(1, 2) = "Score" $sheet.Cells.Item(2, 1) = "Alice" $sheet.Cells.Item(2, 2) = 95
四、まとめ
| 適用タイプ | 実際の用途 | 技術ポイント |
|---|---|---|
| ローカル自動化 | 一括リネーム、ファイルクリーンアップ、システム情報 | ファイルシステム、タイマー、オブジェクト |
| ログ分析 | エラーログを確認し、レポートを生成する | テキスト処理、フィルタリング、エクスポート |
| リモート運用 | 複数ホストでの一括操作、リモートセッション | Invoke-Command, PSSession |
| 技術統合 | REST API、データベース、Excel との連携 | Invoke-RestMethod, COM, ADO.NET |
| .NET サポート | 低レベル API を呼び出して拡張機能を実現する | .NET クラスライブラリを使用 |