Call me stupid, but I'm losing my hair with this one.
I have two results from a Get-WmiObject:
$cpu = Get-WmiObject -Class Win32_Processor
$mb = Get-WmiObject -Class Win32_BaseBoard
Now, I can filter and output a CSV file from each one:
$cpu | Select-Object Name, Description | ConvertTo-Csv -NoTypeInformation
and
$mb | Select-Object Manufacturer, Product | ConvertTo-Csv -NoTypeInformation
But... How the hell could I join these two outputs and make a single CSV output from both? Something like:
(
($cpu | Select-Object Name, Description) +
($mb | Select-Object Manufacturer, Product)
) | ConvertTo-Csv -NoTypeInformation
(of course, this syntax is invalid. Just to show the point)
The -Join operator is used in PowerShell to combine the set of strings into a single string. The strings are combined in the same order in which they appear in the command. The following two statements are the syntax to use the Join operator: -Join <String>
The join operator concatenates a set of strings into a single string. The strings are appended to the resulting string in the order that they appear in the command.
In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator.
You need Powershell V2 for the following.
$cpu = Get-WmiObject -Class Win32_Processor
$mb = Get-WmiObject -Class Win32_BaseBoard
$props = @{
Name = $cpu.Name
Description = $cpu.Description
Manufacturer = $mb.Manufacturer
Product = $mb.Product
}
New-Object PSObject -Property $props | ConvertTo-Csv -NoTypeInformation
There's a Join-Object
function on PoshCode for doing this, but it's buried inside Join-Collection
and not exported.
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(Position=1,ValueFromPipeline=$true)]
$Second
)
BEGIN {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
Process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
Once you've defined that, you can use it like this:
Join-Object (Get-WmiObject -Class Win32_Processor) (Get-WmiObject -Class Win32_BaseBoard) |
Select Name, Description, Manufacturer, Product
Or keep your variables, and do it like:
$cpu = Get-WmiObject -Class Win32_Processor
$mb = Get-WmiObject -Class Win32_BaseBoard
Join-Object $cpu $mb | Select Name, Description, Manufacturer, Product
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With