0

Here is the my code of my function :

function RetrieveServiceStatus ($cptlist, $service) {
    #function var
    $servicestatus = @()
    $cptlist | ForEach-Object { 
        $serviceobj = Get-Service -DisplayName $service -ComputerName $_
        $statusrow = New-Object PSObject
        $statusrow | Add-Member -Type NoteProperty -Name Computer -Value $_
        $statusrow | Add-Member -Type NoteProperty -Name Status $serviceobj.Status
        $statusrow | Add-Member -Type NoteProperty -Name service -Value $service
        $servicestatus += $statusrow
    }
    $servicestatus 
}

This function is called within a loop, when i call this function everything works well... Except the last line, which is supposed to show me my result. The result is showing up on the next occurence of the loop. Do you have any idea why?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Don't really know why, but if i change $servicestatus with $servicestatus | format-table it is working properly. If someone can explain to me. – Alexandre.L Jan 26 '18 at 15:19
  • 1
    It does not render your output because it still waits for more items to decide on column width: https://stackoverflow.com/a/34858911 – user4003407 Jan 26 '18 at 15:21
  • 1
    Side note: why not simply run `Get-Service -DisplayName $service -ComputerName $cptlist | Select-Object MachineName, DisplayName, Status`? – Ansgar Wiechers Jan 26 '18 at 15:24
  • Try `RetrieveServiceStatus -cptlist $something -service $somethingelse | format-table Computer, Status, Service`. i.e. this ensures that after calling the function and returning the above info to the pipeline, you explicitly do something to output it (otherwise as @PetSerAI says, the system may not work as expected). – JohnLBevan Jan 26 '18 at 15:32
  • 1
    Thanks you both, PetSerAl for answering my question and Ansgar for showing me that i can pass my array directly to Get-service – Alexandre.L Jan 26 '18 at 15:33
  • Also, instead of creating an empty array (`$servicestatus`) and adding to it; just output `$statusrow` to the pipeline; that'll be more efficient (or do as @AnsgarWiechers mentions for even more efficiency, if you don't need to create any new properties which don't already exist on the service object). – JohnLBevan Jan 26 '18 at 15:34

0 Answers0