【问题标题】:Powershell howto Get-Process and write output using switch instead of if statementPowershell howto Get-Process and write output using switch 而不是 if 语句
【发布时间】:2014-05-16 02:44:14
【问题描述】:

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

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

【问题讨论】:

  • 尝试在 PowerShell 中输入:help about_switch

标签: powershell if-statement foreach switch-statement


【解决方案1】:

我认为您不需要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"})"

【讨论】:

    【解决方案2】:

    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,我假设这是您所期望的仅有的两种状态,而任何其他状态都是异常的。 Default 条件将选择处于 Running 或 Stopped 之外的任何状态的服务,并为这些服务生成警告。

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多