Kunal Majumder
Kunal Majumder

Reputation: 27

How to create newline on csv file from powershell

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... :(

Upvotes: 1

Views: 2129

Answers (2)

Esperento57
Esperento57

Reputation: 17492

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

Upvotes: 1

G42
G42

Reputation: 10017

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

Upvotes: 2

Related Questions