How to Join PsCustomObjects OR Append Elements to the TOP of an Existing PsCustomObject For Export to CSV

Shell 21 Reputation points
2021-10-30T08:20:34.997+00:00

How do we join PSCustomObjects or append new items to be start (not end) of an existing PSCustomObject please?

Basic example

$matchFound    = $true
$invalidAddress = $true

# This object will have approx 4 fields in it - reasons why a record is invalid
$myObj1 = [PSCustomObject]@{
        MatchFound      = "True"
        InvalidAddress  = "True"
    }


# This object will have approx 50 fields in it
$myObj2 = [PSCustomObject]@{
        FirstName       = "Bill"
        Surname         = "Jones"
    }

# VALID RECORDS:
#$myObj2 | export-csv "C:\temp6\valid.csv" -NoTypeInformation -Append

# INVALID RECORDS:
#$myObj1,$myObj2 | export-csv "C:\temp6\invalid.csv" -NoTypeInformation -Append
# OR 
#$matchFound,$invalidAddress,$myObj2 | export-csv "C:\temp6\invalid.csv" -NoTypeInformation -Append

<#
MatchFound  InvalidAddress  Firstname  Surname
----        -----           ----       -----
True        True           Bill       Jones
#>

eg:
If $myObj1 contains MatchFound = True and InvalidAddress = False, then I only want to append $myObj2 to a csv file (eg: valid.csv)
else I want to append a combination of both objects ($myObj1 and $myObj2) to a single line in a csv file (eg: invalid.csv)

Thanks

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2021-10-30T19:52:57.22+00:00

    Here's one way to do it -- Don't use PSCustomObjects until you need them. Use an ordered hash and use them to create the PSCustomObjects when you need them.

    # invalid hash
    $o1 = [ordered]@{
        MatchFound      = "True"
        InvalidAddress  = "True"
    }
    #valid hash
    $o2 = [ordered]@{
        FirstName       = "Bill"
        Surname         = "Jones"
        C3 = "cp"
        XX50 = "xxp"
    }
    [PSCustomObject]$o2 | Export-Csv c:\junk\valid.csv -NoTypeInformation
    
    
    $o3 = [ordered]@{}
    $o1, $o2 |
        ForEach-Object{
            $_.GetEnumerator() |
                ForEach-Object{
                    $o3[$_.Key] = $_.Value
                }
        }
    [PSCustomObject]$o3 | Export-Csv c:\junk\invalid.csv -NoTypeInformation
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.