Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

応用編:システム管理・REST API連携と自動化

システム管理の基本となるプロセス・サービスの制御、Web API との通信、PowerShell 7 の強力な並行処理、およびスクリプトの自動実行手法を解説します。

プロセスとサービスの管理

実行中のプログラムやシステム常駐サービスの状態監視と制御を行います。

» プロセスの監視と終了

# メモリ使用量の多い上位5プロセスを抽出
Get-Process | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First 5

# 特定の名前のプロセスを安全に停止
Stop-Process -Name "notepad" -Force -ErrorAction SilentlyContinue

» サービスの制御

# サービスの状態確認
Get-Service -Name "wuauserv"

# サービスの再起動
Restart-Service -Name "wuauserv"

REST API との連携

PowerShell には、Web API とやり取りするためのコマンドレットが標準で備わっています。

» Invoke-RestMethod(API からのデータ取得)

JSON や XML 形式のレスポンスを自動的に .NET オブジェクトへ変換して返します。

# GitHub API からリポジトリ情報を取得
$uri = "https://api.github.com/repos/powershell/powershell"
$repo = Invoke-RestMethod -Uri $uri -Method Get

Write-Output "Stars: $($repo.stargazers_count)"
Write-Output "Forks: $($repo.forks_count)"

» 認証ヘッダーと POST リクエスト

API トークンを用いた認証やデータの送信も容易に行えます。

$headers = @{
    Authorization = "Bearer your_token_here"
    "Content-Type" = "application/json"
}

$body = @{
    title = "Bug report"
    body  = "Discovered issue during build"
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri "https://api.example.com/issues" `
    -Method Post `
    -Headers $headers `
    -Body $body

バックグラウンドジョブと並行処理

大量の処理を非同期または並列で実行することで、スクリプト全体の所要時間を大幅に短縮できます。

» PowerShell 7 の並行処理(ForEach-Object -Parallel)

PowerShell 7 から導入されたスレッドベースの並行処理機能です。従来のプロセスベースのジョブに比べて起動が極めて高速で、メモリ消費も抑えられます。

$urls = @(
    "https://www.google.com",
    "https://www.microsoft.com",
    "https://github.com"
)

# 最大3スレッドで同時にリクエストを送信
$urls | ForEach-Object -Parallel {
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    $res = Invoke-WebRequest -Uri $_ -Method Head -TimeoutSec 5
    $sw.Stop()
    [PSCustomObject]@{
        Url      = $_
        Status   = $res.StatusCode
        Duration = $sw.ElapsedMilliseconds
    }
} -ThrottleLimit 3

並行処理ブロックの中から外側の変数を参照する場合は、$using:変数名 というスコープ修飾子を使用します。

スクリプトの自動実行と無人運用

タスクスケジューラや CI/CD パイプラインでスクリプトを安全に自動実行するためのパラメータ設定です。

pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "./backup.ps1"
  • -NoProfile: ユーザープロファイル(起動時設定)の読み込みをスキップし、起動速度と再現性を向上
  • -NonInteractive: ユーザーに入力を求めるプロンプトを抑制し、ハングアップを防止
  • -ExecutionPolicy Bypass: 実行ポリシーによる制約を一時的にバイパス