Exporting a variable to a .csv file

≡放荡痞女 提交于 2020-01-16 04:21:27

问题


I extract a list of departments from AD like this using PowerShell:

$departments = Get-ADUser -Filter * -Property Department |
               Where-Object { $_.Department } |
               Select -Expand Department -Unique

At the end of this operation, if I input on the console $departments I get all the names of the departments as I wished. But if I try to export this to a .csv file using

| Export-Csv H:\TEST\DEPTAAAAA.csv

I get this

#TYPE System.String
Length
4
9
5
13
13
13

How can I export the department names stored in the $departments so the output is a .csv file containing the department names?


回答1:


The Export-Csv cmdlet exports the properties of the input objects as the fields of the output CSV. Since your input is a list of string objects the output is the property (Length) of these objects.

Don't expand the property Department if you want to export it via Export-Csv:

$departments = Get-ADUser -Filter * -Property Department |
               Where-Object { $_.Department } |
               Select Department -Unique

$departments | Export-Csv 'H:\TEST\DEPTAAAAA.csv'

or use Out-File instead of Export-Csv if you want to write the list of strings to the output file:

$departments = Get-ADUser -Filter * -Property Department |
               Where-Object { $_.Department } |
               Select -Expand Department -Unique

$departments | Out-File 'H:\TEST\DEPTAAAAA.csv'


来源:https://stackoverflow.com/questions/32459269/exporting-a-variable-to-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!