PowerShell スクリプト基本構文チートシート

1. コメント・ファイル先頭

# 単一行コメント

<#
複数行コメント
#>

# UTF-8 BOM で保存(PowerShell 5.1 での推奨設定)

2. 変数・文字列・配列・ハッシュテーブル

$name = "Taro"
$age  = 20

# 展開あり文字列(ダブルクォート)
$message = "Name: $name, Age: $age"

# 展開なし文字列(シングルクォート)
$raw = 'Path: C:\Temp\file.txt'

# 配列
$numbers = 1, 2, 3, 4

# ハッシュテーブル
$user = @{
    Name = "Taro"
    Age  = 20
}

3. 基本的な出力・入力

# コンソール出力
Write-Host "Hello"
Write-Output "Pipeline に流す出力"

# 標準入力(対話)
$name = Read-Host "名前を入力してください"

4. 条件分岐 if / elseif / else

$value = 10

if ($value -gt 10) {
    Write-Host "10 より大きい"
}
elseif ($value -eq 10) {
    Write-Host "10 と等しい"
}
else {
    Write-Host "10 より小さい"
}

5. ループ構文(foreach / for / while)

# foreach
$items = 1..5
foreach ($i in $items) {
    Write-Host "Value: $i"
}

# for
for ($i = 0; $i -lt 5; $i++) {
    Write-Host "Index: $i"
}

# while
$count = 0
while ($count -lt 3) {
    Write-Host "Count: $count"
    $count++
}

6. 関数定義

function Add-Numbers {
    param(
        [int]$A,
        [int]$B
    )

    $A + $B
}

$result = Add-Numbers -A 3 -B 5
Write-Host "Result = $result"

7. パラメータ付きスクリプト(param ブロック)

param(
    [string]$InputPath,
    [string]$OutputPath = "result.txt"
)

Write-Host "Input : $InputPath"
Write-Host "Output: $OutputPath"

8. パイプラインと Where-Object / Select-Object

# 例:プロセス一覧からメモリ使用量が大きいものを抽出
Get-Process |
    Where-Object { $_.WorkingSet -gt 200MB } |
    Select-Object -Property Name, Id, WorkingSet

9. 例外処理 try / catch / finally

try {
    $content = Get-Content -Path "C:\no_such_file.txt" -ErrorAction Stop
}
catch {
    Write-Host "エラー発生: $($_.Exception.Message)"
}
finally {
    Write-Host "後処理をここに書く"
}

10. ファイル入出力(文字コードを意識)

# 読み込み(Shift_JIS の場合)
$data = Get-Content -Path "input.txt" -Encoding Default

# 書き込み(Shift_JIS)
Set-Content -Path "output.txt" -Value $data -Encoding Default

# CSV 読み込み・書き込み(Shift_JIS)
$rows = Import-Csv -Path "data.csv" -Encoding Default
$rows | Export-Csv -Path "out.csv" -Encoding Default -NoTypeInformation