How to get Script output piped into export-csv

Good afternoon experts,
What would be the best way to get the output of the following script Piped into export-csv? Any help would be appreciated.
Thank you
Norm

#computers_in_each_scom_group

$computers = Get-SCOMAgent | sort-object DisplayName -Unique -Descending

foreach ($computer in $computers)
{
$ComputerFQDN = $computer.displayname

$Groups = Get-SCOMGroup

write-host "  "

Write-Host $ComputerFQDN "is member of the following Groups:"

Write-Host "============================================================================="



Foreach ($Group in $Groups){

$Members = $Group.GetRelatedMonitoringObjects()

Foreach ($Member in $Members){

If ($Member.DisplayName -eq $ComputerFQDN) {

Write-Host $Group.DisplayName

}

}

}

If your environment is as nearly as complex as mine your code would run for hours probably because you query the groups again and again and again for every single agent you’ve found. I think the key for your task is data reduction. First you query all agents and all groups and save them in variables. Then you build a “matrix” of groups and the displaynames of their related monitoring objects. Then you can iterate over all agents and check if their displaynames are contained in the collected displaynames of the “GroupMatrix”.

$AllAgents = Get-SCOMAgent
$AllGroups = Get-SCOMGroup

$GroupMatrix = foreach ($Group in $AllGroups) {
[PSCustomObject]@{
Group = $Group.DisplayName
Members = $Group.GetRelatedMonitoringObjects().DisplayName
}
}

$Result = foreach ($Agent in $AllAgents) {
$Groups = Foreach ($MatrixGroup in $GroupMatrix) {
if ($MatrixGroup.Members -contains $Agent.displayname) {
$MatrixGroup.Group
}
}
[PSCustomObject]@{
Agent = $Agent.displayname
Groups = $Groups -join ‘,’
}
}
$Result |
Format-Table -AutoSize


The longest running task is the build process of the “GroupMatrix” … at least in my environment.

Hi Olaf,
Your script worked! Thank you for your response.

Norm