I'm trying to create a union of multiple tables in Powershell to output in a user-friendly format as a report, similar to a UNION query in SQL.
I have the following code:
$ft = @{auto=$true; Property=@("MachineName", "Status", "Name", "DisplayName")}
$hosts = @("svr001", "svr002")
$report = @()
ForEach ($h in $hosts) {
$results = Get-Service -CN $h -Name MyService
$report += $results | Format-Table @ft
# Other things occur here, which is why I'm creating $report for output later.
}
Write-Output $report
The output of this code is as follows:
MachineName Status Name DisplayName
----------- ------ ---- -----------
svr001 Running MyService MyServiceDisplayName
MachineName Status Name DisplayName
----------- ------ ---- -----------
svr002 Running MyService MyServiceDisplayName
Since you simply add arrays to do a union in Powershell (i.e.,
$union = @(0, 1, 2) + @(3, 4, 5)), my initial thought was that I should
get the following output:
MachineName Status Name DisplayName
----------- ------ ---- -----------
svr001 Running MyService MyServiceDisplayName
svr002 Running MyService MyServiceDisplayName
In retrospect, I think I understand why I do not get this output, but I'm unclear how to create a union of the two tables from the first output example into a single table as in the second, and I haven't been able to locate anything in the docs or examples online that would send me in the right direction.
| Format-Table .......to the last line afterwrite-output $report. Never save output fromformat-*cmdlets.Format-*cmdlets, doing that generates the following output:System.ServiceProcess.ServiceController System.ServiceProcess.ServiceController System.ServiceProcess.ServiceControllerSystem.ServiceProcess.ServiceController System.ServiceProcess.ServiceController System.ServiceProcess.ServiceController.