Home > Software engineering >  If not run after get-service in powershell
If not run after get-service in powershell

Time:02-17

I'm trying to access the service status of the remote server. i wrote this

$ServerList = get-content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList) 
{
  $Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -like "SQL Server (*"} |        select Status | format-wide
  if($st -eq "Running")
  { 
    $SeverName
    $Status
  }
  else
  {
  }
}

it is showing

$Status= Get-Service -ComputerName $ServerName | ?{$_.DisplayName -li ...
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : NotSpecified: (:) [Get-Service], InvalidOperationException
      FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand

in error. i don't know what i am missing. but when i run without if condition if shows proper output.

CodePudding user response:

$ServerList = Get-Content -Path "c:\users\cont015\Desktop\ServerList.txt"
ForEach ($ServerName in $ServerList) 
{
  $Status= @(
    Get-Service -ComputerName $ServerName -DisplayName "SQL Server (*" |
        Select-Object -ExpandProperty Status)
  if ("Running" -in $Status) 
  {
     [PSCustomObject]@{
        Server = $ServerName
        Status = $Status
     }
  }
  else
  {
  }
}

Explanation:

  • Get-Service docs: -DisplayName Specifies, as a string array, the display names of services to be retrieved. Wildcards are permitted (used instead of Where-Object as such filtering is always faster).
  • Array subexpression operator @( ). - Returns the result of one or more statements as an array. The result is always an array of 0 or more objects (i.e. force Powershell to always return an array when a call returns only one object or even $null)
  • Used [PSCustomObject]@{} in output instead of a sequence of strings (learn advantages at Everything you wanted to know about PSCustomObject).
  • Related