Your code doesn't work, mainly because you are creating a series of variables that in the end you do not use.
To output to CSV, you need to collect objects with properties, not single variables.
A very elegant way is to create those objects using [PsCustomObject]
syntax, where at the same time the order in which you set the properties make up for the order in the final output file.
Using the colon as delimiter character is unusual and may get you into trouble when other applications need to read and understand this, but that is up to you.
Another thing is that you mainly seem to use LDAP attribute names, where PowerShell has most of them mapped to more friendly attribute names (like 'City' which maps to LDAP 'l').
Your code revised:
# Get-ADUSer already returns these properties by default:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# your hardcoded static variables:
$Language = "german"
$Comment = ""
$Link = ""
$gender = ""
$exportto = "C:\Temp\Export01.csv"
# these are the extra properties you want to fetch
$userprops = 'EmailAddress','Title','Company','City','Department','MobilePhone'
# if you want this for all users, remove "-Identity 'm.mustermann'" and use "-Filter *" instead
$result = Get-ADUser -Identity 'm.mustermann' -Properties $userprops | ForEach-Object {
# output an object to be collected in variable $result
# the order in which you put them also determines the field order in the CSV
[PsCustomObject]@{
MailAddress = $_.EmailAddress
FullName = $_.DisplayName
Title = $_.Title
Company = $_.Company
Location = $_.City
Comment = $Comment # static field
Link = $Link # static field
MobilePhone = $_.MobilePhone
Language = $Language # static field
Department = $_.Department
GivenName = $_.GivenName
Surname = $_.Surname
}
}
$result | Export-CSV -Path $exportto -NoTypeInformation -Delimiter ":" -Encoding UTF8
A note about Export-Csv
:
Export-Csv
will always quote everything, be it a header or data field.
Simply trying to remove all quotes in a CSV file is risking mis-alignment in the field order and rendering the csv as unusable.
With PowerShell version 7 you have the option to use parameter -UseQuotes AsNeeded
, but for older versions, you may safely do this using my function ConvertTo-CsvNoQuotes
Since this code is all about getting AD information, I don't see why you would want to construct the FullName here. Just use the DisplayName property that is set in the AD as the code above does