Powershell如何使用switch而不是if语句来处理和写入输出

时间:2014-05-16 02:44:15

标签: powershell if-statement foreach switch-statement

我不知道我的切换语法是否接近。我使用数字来使用开关。我非常感谢任何帮助。我想将我的foreach if语句替换为单个开关。

Set-StrictMode –Version Latest

$services = @( 'DHCP', 'browser', 'TapiSrv', 'lanmanserver', 'spooler', 'lanmanworkstation' )
$serv1 = Get-Service $services

foreach ($service in $services) { 
if ( $serv1.Status -eq 'Running') {  
Write-Host $service is running.
}
}

foreach ($service in $services) {
if ( $serv1.Status -eq 'Stopped') {
Write-Host $service is stopped.
}
}


switch ($serv1.Status) {
Running Write-Host $service is running. | foreach ($service in $services)
Stopped Write-Host $service is stopped. | foreach ($service in $services) 
}

2 个答案:

答案 0 :(得分:2)

我认为你不需要switch/case,使用where-object CmdLet(别名:Where)来过滤你的列表怎么样:

Get-Service $services |where {$_.Status -eq "running"}

你可以在:

中使用它
write-host "Running services : $(Get-Service $services |where {$_.Status -eq "running"})"
write-host "Stopped services : $(Get-Service $services |where {$_.Status -eq "stopped"})"

答案 1 :(得分:0)

Switch实现可能如下所示:

foreach ($service in Get-Service)
{
 Switch ($service.Status)
  {
    'Running'  { Write-Host "$($Service.name) is running." }
    'Stopped'  { Write-Host "$($Service.name) is stopped." }
     Default   { Write-Warning "$($Service.name) is in an unrecognized state." }
  }
}

由于你只是在测试Running或Stopped,我假设这是你期望的唯一两个状态,而其他任何状态都会出现异常。默认条件将选择处于“正在运行”或“已停止”状态之外的任何服务,并为这些服务生成警告。