Switch 문
Coddy PowerShell 여정의 PowerShell 기초 섹션에 포함된 레슨. 28개 중 14번째.
switch는 하나의 값을 케이스 목록과 비교하여 일치하는 각 케이스의 블록을 실행합니다. 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을 출력합니다.
챌린지
쉬움작은 서비스 스크립트의 명령 처리기를 작성하세요.
Command프롬프트로 명령을 읽습니다.start인 경우Starting the service를 출력합니다.stop인 경우Stopping the service를 출력합니다.status인 경우The service is running를 출력합니다.- 그 외의 경우에는
Unknown command:뒤에 입력된 명령을 이어서 출력합니다.
명령은 대소문자를 구분하지 않고 일치하므로 STOP은 stop과 동일하게 작동합니다. STOP을 입력하면 스크립트는 다음을 출력합니다:
Command: STOP
Stopping the servicerestart를 입력하면 두 번째 줄은 Unknown command: restart가 됩니다.
직접 해보기
$cmd = Read-Host "Command"
# switch 문으로 start, stop, status 및 기타 모든 작업을 처리합니다
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.