I have a 2 string outputs that stored in variables like this. Need each line in string 2 to be stored in different rows of csv.
String 1 $var1 89631
String 2 $var2
0236593
None
66398553
996325
None
369318
66935
Tried to convert string 2 in to an array as I need to get them in different rows.
$Newvar2= $var2 -replace("`n",",")
$Var2Array=@($Newvar2)
$objresult= New-Object PSObject -Property @{"Id number"=$var1; "Orders"=$var2Array} | Export-Csv -NoTypeInformation
But in the csv the string data data is getting stored in a single row, where as I need them in different rows. Also tried to Add-Content but it also stores the string in one single row.
$Var2array=($var2 -split '\r?\n').Trim()
Add-Content -path $filepath -value "'"$var1'",'"$var2array'""
Desired output (orders in different rows) csv file-
Id number,Orders
89631,0236593
,None
,66398553
,996325
,None
,369318
,66935
Output I am getting (orders in one row) csv file-
Id number",Orders
89631,0236593
None
66398553
996325
None
369318
66935
CodePudding user response:
If you want the $var1 to be the same on each row, you could do something like:
$var1 = 89631
$var2 = Get-Content "path to orders"
$var2 | Foreach-Object {
New-Object PSObject -Property @{"Id number"=$var1; "Orders"=$_} | Export-Csv -NoTypeInformation -Append
}
Output (CSV File):
"Id number","Orders"
"89631","0236593"
"89631","None"
"89631","66398553 "
"89631","996325"
"89631","None"
"89631","369318"
"89631","66935 "
CodePudding user response:
Here is one way you could do it, note the use of -split
operator to convert the string stored in $var2
into an array.
$var1 = 89631
$var2 = @'
0236593
None
66398553
996325
None
369318
66935
'@
# convert the string into an array
$var2 = $var2 -split '\r?\n'
0..([math]::Max($var1.Count, $var2.Count) - 1) | ForEach-Object {
[pscustomobject]@{
'Id number' = $var1[$_]
'Orders' = $var2[$_]
}
}
The output would become:
Id number Orders
--------- ------
89631 0236593
None
66398553
996325
None
369318
66935
You can then pipe the result of the loop to Export-Csv
to get the desired result.