1

I am stuck on a point where I have two array variables like this

$name = @("A","B","C")

$roll = @("1","2","3")

and I am trying to make a csv file with this data. I am using this code

$name = @("A","B","C")
$roll = @("1","2","3")
$report = New-Object psobject
$report | Add-Member -MemberType NoteProperty -Name "Name" -Value "$name"
$report | Add-Member -MemberType NoteProperty -Name "Roll" -Value "$roll"
$report | Export-Csv -Path "C:\Users\Abby\Desktop\r.csv" -NoTypeInformation 

But I have a output like this

NAME | ROll

A B C| 1 2 3

I want my output like this

NAME | ROll

A | 1

B | 2

C | 3

Can any one have any idea how to do these... Please help me... :(

2 Answers 2

2

You current code is creating the object, and adding the arrays $name and $roll as single entries.

It sounds like you want an entry for each value in your array. Assuming the arrays are the same length, you could iterate over the values:

$name = @("A","B","C")
$roll = @("1","2","3")

foreach($i in 0..($name.Count -1)){
    [array]$report += [pscustomobject] @{
        Name = $name[$i]
        Roll = $roll[$i]
    }
}

# screen output
# $report | Format-Table

$report | Export-Csv -Path "C:\Users\Abby\Desktop\r.csv" -NoTypeInformation

Screen Output

Name Roll
---- ----
A    1
B    2
C    3
Sign up to request clarification or add additional context in comments.

1 Comment

@KunalMajumder NP! If it's resolved your issue, please consider accepting
1

try this:

$name = "A","B","C"
$roll = "1","2","3" 
$index = 0
$name | %{[pscustomobject]@{Name=$_;Roll=$roll[$index++]}} |Export-csv "C:\Users\Abby\Desktop\r.csv" -NoType

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.