Home > front end >  Get AD User info with domain name (Domain\user) with CSV output
Get AD User info with domain name (Domain\user) with CSV output

Time:11-30

I am trying to export Users from AD groups as I would like to get the username as Domain\User for all AD group users. but now I not sure, how to export them to csv for the below. I get the blank output

Please help!!

$ADGroups = Get-ADGroup 'myadgroup1'
$result = Get-ADGroupMember -Identity $ADGroups | foreach-object {
$username = $_.SamAccountName
$distinguishedName = $_.distinguishedName
$dc = [regex]::Match($distinguishedName, 'DC=([^,|$] )').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
Write-Host $ADGroups.Name $domainuser
}
$reult | Export-Csv ".\userinfo.csv" -NoTypeInformation -UseCulture

CodePudding user response:

I basically use what you have with some modifications. You will need to create a list object and then within the loop add items to that list. I take your $domainuser and add it to $domainusers on each iteration of the loop, so you end up with the formatted list of usernames.

Exporting the list to a csv was giving me issues. If I'm understanding correctly what happened is that the list of strings only had a property of "length" so the csv file only contained the length of each individual string. Since Export-CSV takes objects and outputs the properties you need to convert the strings into objects and then it can be exported to csv. reference

# create an array list object so we can add to it in the loop
$domainusers = New-Object System.Collections.Generic.List[System.Object]

$ADGroups = Get-ADGroup "myadgroup1"

Get-ADGroupMember -Identity $ADGroups | foreach-object {
$username = $_.SamAccountName
$distinguishedName = $_.distinguishedName
$dc = [regex]::Match($distinguishedName, 'DC=([^,|$] )').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username

# add formatted string to the list
$domainusers.ADD($domainuser)
}

Write-host ($domainusers |Format-List |out-String)

#  First convert strings to objects. 
$obj_list = $domainusers| Select-Object @{Name='username';Expression={$_}}
# convert object list to csv
$obj_list | Export-Csv ".\userinfo.csv" -NoType
  • Related