简体   繁体   English

Powershell-将多行字符串导出到csv中的不同行

[英]Powershell- export a multiple line string to different rows in csv

I have a 2 string outputs that stored in variables like this.我有 2 个字符串输出,它们存储在这样的变量中。 Need each line in string 2 to be stored in different rows of csv.需要将字符串 2 中的每一行存储在不同的 csv 行中。 String 1 $var1 89631 String 2 $var2字符串 1 $var1 89631字符串 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.试图将字符串 2 转换为数组,因为我需要将它们放在不同的行中。

$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.但是在 csv 中,字符串数据数据存储在一行中,而我需要它们在不同的行中。 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-所需的输出(不同行中的订单)csv文件-

Id number,Orders
89631,0236593
      ,None
      ,66398553 
      ,996325
      ,None
      ,369318
      ,66935 

Output I am getting (orders in one row) csv file-我得到的输出(一行订单)csv文件-

Id number",Orders
89631,0236593
        None
        66398553 
        996325
        None
        369318
        66935 

If you want the $var1 to be the same on each row, you could do something like:如果您希望 $var1 在每一行上都相同,您可以执行以下操作:

$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):输出(CSV 文件):

"Id number","Orders"
"89631","0236593"
"89631","None"
"89631","66398553 "
"89631","996325"
"89631","None"
"89631","369318"
"89631","66935 "

Here is one way you could do it, note the use of -split operator to convert the string stored in $var2 into an array.这是您可以做到的一种方法,请注意使用-split运算符将存储在$var2中的字符串转换为数组。

$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.然后,您可以将循环的结果通过管道传输到Export-Csv以获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM