Get-Service with if/else checks

Landon,
Welcome to the forum. :wave:t4:

Since I like re-usable output I’d use a slightly different approach and avoid Write-Host prosa with fancy colors … :wink:

Besides this I’d recommend to avoid connecting to one computer more than once at a time.

$ComputerList = Get-Content -Path 'C:\<file location>\Desktop\Machines.txt'
$ServiceQueryList = Get-Content -Path 'C:\<file location>\ServiceList.txt'

$Result =
foreach ($ComputerName in $ComputerList) {
    if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
        Invoke-Command -ComputerName $ComputerName -ScriptBlock {
            $ServiceList = 
                Get-Service -Name $USING:ServiceQueryList -ErrorAction SilentlyContinue
            foreach ($Service in $USING:ServiceQueryList) {
                $ServiceMatrix = 
                [ordered]@{
                    Name         = ''
                    Installed    = $false
                    Status       = 'n/a'
                    DisplayName  = 'n/a'
                }
                
                if ($Service -in $ServiceList.Name ) {
                    $CurrentService = 
                        $ServiceList | 
                            Where-Object -Property Name -EQ -Value $Service
            
                    $ServiceMatrix.Name = $CurrentService.Name
                    $ServiceMatrix.Status = $CurrentService.Status
                    $ServiceMatrix.Installed = $true
                    $ServiceMatrix.DisplayName = $CurrentService.DisplayName
                }
                else {
                    $ServiceMatrix.Name = $Service
                }
                [PSCustomObject]$ServiceMatrix

                $ServiceList | 
                    Where-Object -Property Status -EQ -Value Stopped | 
                        Start-Service -ErrorAction SilentlyContinue
            }
        } | 
            Select-Object PSComputerName, Name, Installed, Status, DisplayName
    }
    else {
        $ComputerUnreachableList += $ComputerName
    }
}

$Result | 
    Format-Table -AutoSize

'Computers unreachable: {0}' -f ($ComputerUnreachableList -join ', ')

This way you could use the output of the variable $Result to pipe it to Export-Csv for logging purposses or just for documentation. And even if you don’t - it is at least much easier on the eyes. :wink:

And you could use the output of the variable $ComputerUnreachableList for further steps or for investigations why these comptuers are unreachable. :+1:t4:

1 Like