2011-04-01 10 views
5

Cuál es la sintaxis para incluir varios valores en un comando eq:

esto funciona, pero creo que hay una manera de ahorrar algo de tecleo:

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

código Think debe ser similar, pero no me acuerdo exactamente de la sintaxis:

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

Cerrar, en realidad. '" Stopped "," Running "-eq $ _. Status' funcionaría, pero solo porque ninguno de los valores de enumeración es' 0'. – Joey

Respuesta

6

Usted puede utilizar -contains y la gsv alias:

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

EDITAR: También puede utilizar el operador de -match:

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

2.Edit: Una versión más corta, w/agradecimiento especial a @Joey:

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

Y el alias '?'. Y omita el '@()' ya que eso no es necesario. '" Stopped "," Running "' ya es una matriz. – Joey

+0

@Joey Gracias, agregué una versión '?'. –

+4

Bueno, la variante más corta probablemente sería 'gsv |? {1,4-eq $ _. Estado}' usando algunos trucos de golf comunes :-) – Joey

1

La coincidencia basada en grupos regex es la forma más corta y segura de siempre. También puede utilizar el complemento:

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

En este caso, no es el más corto, obviamente; ¡pero alguna vez lo es!

+0

Tenga en cuenta que la lógica correspondiente aquí es 'donde {($ _. Estado -ne" En pausa ") -AND ($ _. Estado -ne" Running_Pending ")} - AND ($ _. Estado -ne" Pause_Pending ")} -AND ($ _. Estado -ne "Stop_Pending")} - AND ($ _. Estado -ne "Continue_Pending")} '. Espero que esto ayude. –

2

Según lo indicado por @OcasoProtal, puede comparar una matriz de estados válidos con su estado objetivo utilizando los operadores -contains o -notcontains.

Estado dado se basa en un tipo de enumeración también puede usar eso (es decir, en lugar de utilizar comparaciones de cadenas). Esto añade una validación adicional (es decir, sin especificar manualmente un ValidateSet), y le permite tirar de una lista de valores de la Enum (por ejemplo, como se muestra en mi código de ejemplo siguiente, donde se especifica 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 

Salida de muestra:.

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 

también puede conseguir fácilmente en trámite o "estado estable" estados de usar algo como esto: salida

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

PendingDemo $true 
"" 
PendingDemo $false 

muestra:

Pending is True 
StartPending 
StopPending 
ContinuePending 
PausePending 

Pending is False 
Stopped 
Running 
Paused 
Cuestiones relacionadas