Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

What is the syntax to include several values in an -eq command:

This works but i think there is a way to save some typing:

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

Think code should look like but i don't remember exactly the syntax:

Get-Service | where {($_.Status -eq "Stopped"|"Running"|"...")}
like image 735
icnivad Avatar asked Apr 01 '11 12:04

icnivad


2 Answers

You can use -contains and the gsv alias :

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

EDIT: You can also use the -match operator:

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

2.EDIT: A shorter version, w/ special thanks to @Joey:

gsv | ? {$_.Status -match "Stopped|Running"}
like image 92
Ocaso Protal Avatar answered Oct 28 '22 15:10

Ocaso Protal


As stated by @OcasoProtal you can compare an array of valid statuses with your target status using the -contains or -notcontains operators.

Given Status is based on an enum type you can also use that (i.e. as opposed to using string comparisons). This adds additional validation (i.e. without manually specifying a ValidateSet), and allows you to pull a list of values from the Enum (e.g. as shown in my sample code below where Not is specified.

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

Sample Output:

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

You can also easily get Pending or "Stable State" statuses using something like this:

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

PendingDemo $true
""
PendingDemo $false

Sample Output:

Pending is True
StartPending
StopPending
ContinuePending
PausePending

Pending is False
Stopped
Running
Paused
like image 32
JohnLBevan Avatar answered Oct 28 '22 16:10

JohnLBevan