Powershell object where the expanded properties become just properties

Viewed 23

I collect two files that both contain an equal number of strings and am trying to join them into 1 object with each being a named propery.

$Users = Get-content C:\temp\Users.txt
$Languages = Get-content C:\temp\Languages.txt

Using the code below:

$myHashtable = @{
    Name     = $user
    Language = $Languages
}
$myObject = [pscustomobject]$myHashtable

The $myObject looks like

Name                        Language                                  
---------                -------------                                  
{Todd, Sara, Mike...} {English, Spanish, French...}

Can I adjust my code in so $MyObject outputs the following?

Name                        Language                                  
---------                ------------- 
Todd                       English
Sara                       Spanish
Mike                       French
1 Answers

Based on your additional information, you could use:

$Users     = Get-content C:\temp\Users.txt
$Languages = Get-content C:\temp\Languages.txt

$MyObjects = $Users | ForEach-Object -Begin {$i=0} -Process {
    [PSCustomObject]@{
        'Name'     = $Users[$i]
        'Language' = $Languages[$i++]
    }
} -End {}

This is fine for working with the whole collecdtion. If you wanted random access to individual elements, a hashtable keyed on 'Name' might be a better idea:

$Users     = Get-content C:\temp\Users.txt
$Languages = Get-content C:\temp\Languages.txt

$MyObjectHashTable = $Users | ForEach-Object -Begin { $hash=@{} ; $i=0 } -Process {
    $hash.Add( $Users[$i] , $Languages[$i++] )
} -End { $hash }
Related