Search code examples
powershellpowershell-2.0reportingeasyhtmlreport

Powershell Only Outputting First Value


I am creating a report for some servers I manage.

I have a lot of other information in the report which I have got how I want, but this has been bugging me for a while - and no matter what I do and where I've searched, I haven't been able to resolve the issue.

The following code checks my 7 servers for any stopped Services starting with "Office Comm" and shows any services which have stopped in a HTML table, however it will only output the FIRST of any stopped services instead of the whole list...I have searched and recoded and tried different methods but have not been able to resolve....any assistance would be GREATLY appreciated!

Write-Host "Getting stopped services snapshot...`n"

$StoppedServicesReport = @()
$StoppedServices = Get-WmiObject -Class Win32_Service -ComputerName $Computers `
    -Filter "displayname like 'Office Comm%' AND state='Stopped'"

foreach ($StoppedService in $StoppedServices) {
    $stoppedRow = New-Object -Type PSObject -Property @{
        Server = $StoppedService.SystemName
        Name = $StoppedService.DisplayName
        Status = $StoppedService.State
    }
    $StoppedServiceReport = $StoppedServiceReport + $stoppedRow
}

$StoppedServiceReport = $StoppedServiceReport | ConvertTo-Html -Fragment

Solution

  • Here is another approach:

    $computers | Foreach-Object {
    
        $computerName = $_
    
        Get-Service -ComputerName $computerName -DisplayName "Office Comm*" |
            Where-Object { $_.Status -eq "Stopped" } |
            Select-Object @{ n = "Server"; e = { $computerName } }, @{ n = "Name"; e = { $_.DisplayName } }, Status
    
    } | ConvertTo-Html -Fragment
    

    See PetSerAl's comment regarding your original error.