【问题标题】:Add-Content to CSV Powershell向 CSV Powershell 添加内容
【发布时间】:2019-03-22 19:19:40
【问题描述】:

当我运行以下代码时,我会在不同的列中获得详细信息列表。

$file = 'c:\output\testing.csv'
   Get-AdUser -filter "DisplayName -eq 'joe bloggs'" | 
   Get-ADUser -Properties * |  
 Select-Object givenName, surname, mail, 
@{ Label = "Country"
Expression = { if ($_.Country) { $_.Country } else { "GB" } }
 ,samaccountname, department, description | Export-csv -path $file

输出(1)如下:

+-----------+---------+-----------------+---------+----------------+------------+-------------+
| givenName | surname |      mail       | Country | samaccountname | department | description |
+-----------+---------+-----------------+---------+----------------+------------+-------------+
| joe       | bloggs  | joe.b@email.com | GB      | bloggsG        | IT         | Support     |
+-----------+---------+-----------------+---------+----------------+------------+-------------+

但是,如果我将 Export-CSV 修改为 Add-Content,则输出 (2) 如下:

+---------------------------------------------------------------------------------------------------------------------------------------+---------+------+---------+----------------+------------+-------------+
|                                                               givenName                                                               | surname | mail | Country | samaccountname | department | description |
| {givenName=Fred; surname=Smith; mail=fred.s@email.com; Country=GB; samaccountname=smithF; department=Facilities; description=cleaner} |         |      |         |                |            |             |
+---------------------------------------------------------------------------------------------------------------------------------------+---------+------+---------+----------------+------------+-------------+

如何使用Add-Content 显示与第一个表相同的输出?

【问题讨论】:

    标签: powershell csv append


    【解决方案1】:

    Add-Content 用于将非结构化文本附加到 文本文件,类似于 Set-Content - 您不能使用它将行附加到现有 CSV 文件

    相反,您必须使用Export-Csv -Append

    ... | Export-Csv -Path $file -Append -Encoding Ascii # pick the proper encoding
    

    字符编码注意事项,自 Windows PowerShell v5.1 起[1]

    • 没有 -Append, Export-Csv 使用 ASCII(!) 编码 - 违反记录的行为。

      • 这意味着非 ASCII 字符被音译为 literal ?,也就是说,您可能丢失信息
    • -Append,奇怪的是,非 ASCII 字符是 UTF-8 编码的 - 与文件的原始编码无关。

    要获得可预测的行为,请始终将 -EncodingExport-Csv 一起明确使用 - 无论是否使用 -Append


    [1] 跨平台的 PowerShell Core 版本不受影响,因为它默认始终使用无 BOM 的 UTF-8 编码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多