Search code examples
powershellcsvscom

How to put different variables into an array to export to a CSV in PowerShell


So I'm pulling a SCOM class to get Management Pack names, then using those MP names to get different monitors. I'm wanting to output the GUID, Monitor Display Name, and Management Pack Name. The problem I'm running into is how to output it into a CSV because I don't know how to separate them into columns. There are hundreds of Monitors, so I believe it needs to be put into an array also.

Currently, I can get it to write to the console in the columns and with the information I need, but when I try to use the Export-CSV cmdlet, it gives me all sorts of errors. Here is what I have so far:

$OMMgmtSrv = "SERVER"
$Classes = Get-SCOMClass -ComputerName $OMMgmtSrv
Foreach ($Class in $Classes)
{
$MP = $Class.ManagementPackName

$monitors = Get-SCOMMonitor -ManagementPack $MP  | sort-object displayname

Foreach($monitor in $monitors)
{

Write-Host $monitor.ID $monitor.displayname $MP

}
}

Solution

  • PowerShell 3.0 or later, you can use a PSCustomObject.

    foreach ($monitor in $monitors) {
        [PSCustomObject]@{
            ID = $monitor.ID
            DisplayName = $monitor.displayname
            ManagementPackName = $MP
        } | Export-Csv -Path "C:\monitors.csv" -Append
    }
    

    This custom object will have custom properties ID, DisplayName, and ManagementPackName, and it will export to a CSV easily.