问题
When I run the below code I get a list of details in separate columns.
$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
Output (1) is as follows:
+-----------+---------+-----------------+---------+----------------+------------+-------------+
| givenName | surname | mail | Country | samaccountname | department | description |
+-----------+---------+-----------------+---------+----------------+------------+-------------+
| joe | bloggs | joe.b@email.com | GB | bloggsG | IT | Support |
+-----------+---------+-----------------+---------+----------------+------------+-------------+
However, if I amend the Export-CSV to Add-Content
, the output (2) is as below:
+---------------------------------------------------------------------------------------------------------------------------------------+---------+------+---------+----------------+------------+-------------+
| givenName | surname | mail | Country | samaccountname | department | description |
| {givenName=Fred; surname=Smith; mail=fred.s@email.com; Country=GB; samaccountname=smithF; department=Facilities; description=cleaner} | | | | | | |
+---------------------------------------------------------------------------------------------------------------------------------------+---------+------+---------+----------------+------------+-------------+
How do I use Add-Content
to show the same output as the first table?
回答1:
Add-Content is for appending unstructured text to a text file, similar to Set-Content
- you cannot use it to append rows to an existing CSV file.
Instead, you must use Export-Csv -Append
:
... | Export-Csv -Path $file -Append -Encoding Ascii # pick the proper encoding
Character-encoding caveats, as of Windows PowerShell v5.1[1]:
Without
-Append
, Export-Csv uses ASCII(!) encoding - against documented behavior.- This means that non-ASCII characters are transliterated to literal
?
, i.e., you may lose information.
- This means that non-ASCII characters are transliterated to literal
With
-Append
, curiously, non-ASCII characters are UTF-8-encoded - irrespective of the file's original encoding.
To get predictable behavior, always use -Encoding
explicitly with Export-Csv
- both with and without -Append
.
[1] The cross-platform PowerShell Core edition is not affected, because it consistently uses BOM-less UTF-8 encoding by default.
来源:https://stackoverflow.com/questions/52866269/add-content-to-csv-powershell