Need similar data in similar series from 2 different variables to export in csv

I have 2 variables with name of $abc and $xyz. $abc has first names and $xyz has last names. I want to have this data in csv format.
$abc[0] should go to $xyz[0] and so on. The csv format should be like below:

Firstname Lastname
Mike Johnson
John Wilson
Sam William

$abc = “Mike”, “John”, “Sam”
$xyz = “Johnson”, “Wilson”, “William”

I have already created the csv file and trying to do below way using nested loops but not getting desired results.

$data = @(
“$abc[0],$xyz[0]”
)

        $data | foreach { Add-Content -Path "C:\temp\test.csv" -Value $_ }

Please help me with loop or any other way to do this.
This is just an example. But I need the data in similar format. Let me know someone wants further information.

A simple For loop should suffice:

$abc = @('Buffy','Willow','Rupert')
$xyz = @('Summers','Rosenberg','Giles')

For ($i = 0; $i -lt $abc.Count; $i++) {
    [PSCustomObject]@{
        FirstName = $abc[$i]
        LastName  = $xyz[$i]
    } | Export-Csv E:\Temp\Files\Names.csv -Append -NoTypeInformation
} 
1 Like

Thank you so much @matt-bloomfield. I was trying to put result in array not in hashtable. It really helped a lot. Thanks again.

Regards
Jatinder

1 Like