Search code examples
powershellcsvactive-directoryhashtable

How to use GetEnumerator() to export hash table to a csv file in PowerShell?


I wrote a search function, which searches for some active directory attributes. I now want to export the content to a .csv file. If I see it correctly, the whole output is a hash table. But when I try to use the GetEnumerator() function, it doesn't do anything.

Can someone help and maybe explain what I did wrong? The code is below. Thanks in advance!

Import-Module ActiveDirectory
$users = Get-ADUser -Filter { employeeNumber -notlike '*' } -Properties memberOf, samAccountName | ForEach-Object -Process { @{ $_.samAccountName = $_.memberOf | Where-Object { $_ -like '*DAT*' } } }
$users.GetEnumerator() |
    Select-Object -Property @{N='AD1';E={$_.Key}},
    @{N='AD2';E={$_.Value}} |
        Export-Csv -NoTypeInformation -Path H:\test123.csv

Solution

  • If you look at your code, you are creating a list of hashtables that contains your SamAccountName and Groups. But, when you use the enumerator, you are only thinking about the hashtable and not the list you created.

    This is how you can iterate through a hashtable. You first create a hash table and add all elements to it.

    $hash = @{}
    Get-ADUser -Filter { employeeNumber -notlike '*' } -Properties memberOf, samAccountName | ForEach-Object -Process { $hash.Add($_.samAccountName, ($_.memberOf | Where-Object { $_ -like '*DAT*' }))  }
    $hash.GetEnumerator() |
        Select-Object -Property @{N='AD1';E={$_.Key}},
        @{N='AD2';E={$_.Value}} |
            Export-Csv -NoTypeInformation -Path H:\test123.csv
    

    Or you can continue with the list of hashtables but change how you are accessing the data. Each element of your list is a single hashtable with Keys (only one in it).

    $users = Get-ADUser -Filter { employeeNumber -notlike '*' } -Properties memberOf, samAccountName | ForEach-Object -Process { @{ $_.samAccountName = $_.memberOf | Where-Object { $_ -like '*DAT*' } } }
    $users.GetEnumerator() |
        Select-Object -Property @{N='AD1';E={$_.Keys[0]}},
        @{N='AD2';E={$_.Values[0]}} |
            Export-Csv -NoTypeInformation -Path H:\test123.csv