简化PS命令:Get-Service |其中{($ _。状态-eq“已停止”)-OR($ _。状态-eq“正在运行”)}

时间:2011-04-01 12:29:02

标签: powershell

在-eq命令中包含多个值的语法是什么:

这有效,但我认为有一种方法可以节省一些打字:

Get-Service | where {($_.Status -eq "Stopped") -OR ($_.Status -eq "Running")}

认为代码应该看起来像但我不记得确切的语法:

Get-Service | where {($_.Status -eq "Stopped"|"Running"|"...")}

3 个答案:

答案 0 :(得分:6)

您可以使用-containsgsv别名:

gsv | where-object {@("Stopped","Running") -contains $_.Status}

编辑:您还可以使用-match运算符:

gsv | where-object {$_.Status -match "Stopped|Running"}

2.EDIT :更短的版本,特别感谢@Joey:

gsv | ? {$_.Status -match "Stopped|Running"}

答案 1 :(得分:2)

正如@OcasoProtal所述,您可以使用-contains-notcontains运算符将一系列有效状态与目标状态进行比较。

鉴于状态基于枚举类型,您也可以使用它(即与使用字符串比较相反)。这会增加额外的验证(即无需手动指定ValidateSet),并允许您从Enum中提取值列表(例如,如下面的示例代码所示,其中指定了Not

clear-host
[string]$ComputerName = $env:COMPUTERNAME
[string]$ServiceName = "MSSQLSERVER"


function Wait-ServiceStatus {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ServiceName
        ,
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$ComputerName = $env:COMPUTERNAME
        ,
        [switch]$Not
        ,
        [Parameter(Mandatory = $true)]
        [System.ServiceProcess.ServiceControllerStatus]$TartgetStatus
    )
    begin {
        [System.ServiceProcess.ServiceControllerStatus[]]$TargetStatuses = @($TartgetStatus)
        if ($Not.IsPresent) {

            #EXAMPLE: Build your comparison array direct from the ENUM
            $TargetStatuses = [Enum]::GetValues([System.ServiceProcess.ServiceControllerStatus]) | ?{$_ -ne $TartgetStatus}

        }
    }
    process {

        #EXAMPLE: Compare status against an array of statuses
        while ($TargetStatuses -notcontains (Get-Service -ComputerName $ComputerName -Name $ServiceName | Select -Expand Status)) {

            write-host "." -NoNewline -ForegroundColor Red
            start-sleep -seconds 1
        }
        write-host ""
        #this is a demo of array of statuses, so won't bother adding code for timeouts / etc 
    }
}
function Write-InfoToHost ($text) {write-host $text -ForegroundColor cyan} #quick thing to make our status updates distinct from function call output

Write-InfoToHost "Report Current Service Status"
get-service -Name $ServiceName -Computer $ComputerName | Select -ExpandProperty Status
Write-InfoToHost ("Stop Service at {0:HH:mm:ss}" -f (get-date))
(Get-WmiObject Win32_Service -Filter "name='$ServiceName'" -Computer $ComputerName).StopService() | out-null #use WMI to prevent waiting
Write-InfoToHost ("Invoked Stop Service at {0:HH:mm:ss}" -f (get-date)) 
Wait-ServiceStatus -ServiceName $ServiceName -TartgetStatus Stopped 
Write-InfoToHost ("Stop Service Completed at {0:HH:mm:ss}" -f (get-date)) 

Write-InfoToHost "Report Current Service Status" 
get-service -Name $ServiceName -Computer $ComputerName | Select -ExpandProperty Status

Write-InfoToHost ("Start Service at {0:HH:mm:ss}" -f (get-date)) 
(Get-WmiObject Win32_Service -Filter "name='$ServiceName'" -Computer $ComputerName).StartService() | out-null  #use WMI to prevent waiting
Write-InfoToHost ("Invoked Start Service at {0:HH:mm:ss}" -f (get-date))
Wait-ServiceStatus -ServiceName $ServiceName -Not -TartgetStatus Stopped 
Write-InfoToHost ("Service Not Stopped at {0:HH:mm:ss}" -f (get-date))
Wait-ServiceStatus -ServiceName $ServiceName -Not -TartgetStatus StartPending
Write-InfoToHost ("Service Not Start-Pending at {0:HH:mm:ss}" -f (get-date))
Write-InfoToHost "Report Current Service Status"
get-service -Name $ServiceName -Computer $ComputerName | Select -ExpandProperty Status

示例输出:

Report Current Service Status
Running
Stop Service at 12:04:49
Invoked Stop Service at 12:04:50
.
Stop Service Completed at 12:04:51
Report Current Service Status
Stopped
Start Service at 12:04:51
Invoked Start Service at 12:04:52

Service Not Stopped at 12:04:52
..
Service Not Start-Pending at 12:04:54
Report Current Service Status
Running

您还可以使用以下内容轻松获得待处理或“稳定状态”状态:

function PendingDemo([bool]$Pending) {
    write-host "Pending is $Pending" -ForegroundColor cyan
    [Enum]::GetValues([System.ServiceProcess.ServiceControllerStatus]) | ?{($_ -notlike "*Pending") -xor $Pending}
}

PendingDemo $true
""
PendingDemo $false

示例输出:

Pending is True
StartPending
StopPending
ContinuePending
PausePending

Pending is False
Stopped
Running
Paused

答案 2 :(得分:1)

基于正则表达式组的匹配始终是最短且最安全的方式。您也可以使用补充:

gsv | ? {$_.status -notmatch "Paused|Running_Pending|Pause_Pending|Stop_Pending|Continue_Pending"}

在这种情况下,它显然不是最短的;但有时它是!