Export variable to CSV file

I am retrieving 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 am on the console $departments, I get all the department names as I wished. But if I try to export this to a CSV file using

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

I get it

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

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

+1
source share
1 answer

The cmdlet Export-Csvexports the properties of the input features as fields in the output CSV. Since your entry is a list of string objects, the result is the property ( Length) of these objects.

Department, Export-Csv:

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

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

Out-File Export-Csv, :

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

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

Source: https://habr.com/ru/post/1676153/


All Articles