Menu
CoddyTech

Switch文

CoddyのPowerShellジャーニー「PowerShellの基礎」セクションの一部。レッスン 14/28。

switch は1つの値を case のリストと比較し、一致する各 case のブロックを実行します。default はどれにも一致しなかった場合に実行されます:

$size = Read-Host "Size"
switch ($size) {
    "S" { Write-Output "Small cup" }
    "M" { Write-Output "Medium cup" }
    "L" { Write-Output "Large cup" }
    default { Write-Output "We have S, M and L" }
}

入力 m の場合、Size: m と Medium cup が出力されます。-eq と同様に、switch は大文字と小文字を区別しません。XL の場合は、We have S, M and L と出力されます。

case は数値にすることもできます。"*.txt" のようなパターンを使用するには、-Wildcard を追加します:

switch -Wildcard ("notes.txt") {
    "*.txt" { Write-Output "Text file" }
    "*.csv" { Write-Output "Data file" }
}

これは Text file と出力します。

challenge icon

チャレンジ

簡単

小さなサービススクリプトのコマンドハンドラーを作成します。

  1. プロンプト Command でコマンドを読み込みます。
  2. start の場合は Starting the service を出力します。stop の場合は Stopping the service を出力します。status の場合は The service is running を出力します。
  3. それ以外の場合は、Unknown command: の後に入力された通りのコマンドを出力します。

コマンドは大文字と小文字を問わず一致するため、STOP は stop と同じように動作します。入力が STOP の場合、スクリプトは以下を出力します:

Command: STOP
Stopping the service

restart の場合、2行目は Unknown command: restart となります。

自分で試してみよう

$cmd = Read-Host "Command"
# start、stop、status、その他の処理を switch で処理する
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

PowerShellの基礎のすべてのレッスン