2014-05-16 19 views
0

我不知道我的開關語法是否接近。我已經使用數字開關。我非常感謝任何幫助。我想將我的foreach替換成單個開關。Powershell如何Get-Process和寫輸出使用開關而不是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) 
} 
+0

嘗試在PowerShell中輸入以下內容:'help about_switch' –

回答

0

一個交換機的實現可能是這個樣子:

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進行測試,因此我認爲這是您期望的唯一兩種狀態,而其他任何狀態都會異常。 「默認」條件將選取「運行」或「已停止」以外的任何服務,併爲這些服務生成警告。

2

我不認爲你塔在你需要switch/case情況下,如何使用where-object cmdlet的(別名:凡)什麼來過濾列表:

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"})"