【问题标题】:How to add an array as a column to csv file using powershell?如何使用powershell将数组作为列添加到csv文件?
【发布时间】:2021-06-25 19:38:15
【问题描述】:

我对 PowerShell 有点陌生。目前我正在尝试从 abd excel 文件中获取列并将它们存储到一个新的 CSV 文件中。

我设法使用以下方法从 excel 中获取了我需要的列:

$emails=$file.Worksheets['Form1'].UsedRange.Rows.Columns[4].Value2 
$Response=$file.Worksheets['Form1'].UsedRange.Rows.Columns[8].Value2

其中$emails $ResponseSystem.array 包含

    email1
...
    email 20

Resp1 ...
Resp20

但是我没有得到这种格式:

Email , Response
----------------
email1, Resp1
Email2, Resp2

改为应用[pscustomobject]@{'emails' = $emails; 'Response' = $Response} 我是这样的:

emails                                          Response
---                                                ---                                                                                                                                          
{Email1, email2 ... email20}               {Resp1..Resp20}

谁能帮我解决这个问题? 非常感谢!!

【问题讨论】:

标签: excel powershell csv


【解决方案1】:

您可以使用简单的for() 循环遍历数组并从中创建对象。
例如,有了对象,您可以轻松地将其写入 CSV 文件。

$emails   = $file.Worksheets['Form1'].UsedRange.Rows.Columns[4].Value2 
$Response = $file.Worksheets['Form1'].UsedRange.Rows.Columns[8].Value2

# use a loop with a counter to go through the arrays element by element
# and output objects. Capture these objects in variable $result
$result = for ($i = 0; $i -lt $emails.Count; $i++) {
    [PsCustomObject]@{
        Email    = $emails[$i]
        Response = $Response[$i]
    }
}

# output on screen
$result

# output to CSV file
$result | Export-Csv -Path 'Path\To\The\results.csv' -NoTypeInformation

在屏幕上,你会得到类似的东西:

Email   Response
-----   --------
email1  Resp1
email2  Resp2

【讨论】:

    【解决方案2】:

    你没有数组。它是一个运行时对象。

    您可以尝试下面的代码来生成 csv 文件。

    $emails = {'test.test.com', 'test1.test.com'}
    $responses = {'testresponse', 'test1response'}
    $emailarray = $emails.ToString().Split(",")
    $emailarray
    $collection = @()
    for($i = 0; $i -lt $emailarray.Length ; $i++)
    {
    $item = @{}
    $item.email = $emails.ToString().Split(",")[$i]
    $item.response = $responses.ToString().Split(",")[$i]
    $collection += New-Object psobject -Property $item
    }
    $collection  | Export-Csv -LiteralPath $yourDestinationpath -NoTypeInformation -Encoding UTF8
    

    【讨论】:

    • 感谢您的回复,实际上在我的情况下,当我执行 $emails.ToString().Split(",") 时,它会将其作为输出: System.Object[] 除了 $emails。 Get-Type() 将 System.Array 作为 BaseType,有什么想法吗?
    • @lheb,在这种情况下,您可以简单地在 for 循环中使用数组,如代码中所述。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2020-01-04
    • 2020-02-26
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多