When incrementing the conveyor variable

I want to

a) Display all results for a given service if found

b) If no services were found at all, display the appropriate error

The code below will achieve a) how can I achieve b) in the neat way possible . Can I expand the tube so that it connects to something like | Set-Variable $ serviceCount ++ and then check this variable and if it is zero display a message?

foreach($service in $services)
{        
    Get-Service | where {$_.Name -eq $service}  
}

      

+3


source to share


1 answer


The -Name

cmdlet parameter Get-Service

takes an array String

s, so you can replace your loop like this:

Get-Service -Name $services

      

To check how many services were returned, you can take the result of the call Get-Service

, convert it to an array (if there isn't one already), and store it in a variable:

$results = @(Get-Service -Name $services)

      



Then check the length of the array:

if ($results.Length -eq 0)
{
    Write-Warning 'No services were found!'
}

      

Note that an error will be thrown for every name passed to the parameter -Name

that does not match the installed service. You can suppress these errors with the parameter -ErrorAction

:

Get-Service -Name $services -ErrorAction SilentlyContinue

      

+4


source







All Articles