Home > Blockchain >  Exporting a list of AD Users and their group through powershell
Exporting a list of AD Users and their group through powershell

Time:11-29

I'm looking to export users with their groups in Active Directory through powershell, but I can't seem to get the pipe to work for some reason the powershell script I'm using right now is


`
$groups = get-adgroup -filter *

foreach ($group in $groups) {
$naam = $group.name
$members = Get-ADGroupMember -identity $group
write-host “Group: $naam”
write-host “————————————-”
foreach ($member in $members) {
$memnaam = $member.samaccountname
write-host “$naammem”
}`

I just can't seem to figure this out any recommendations?

`
$groups = get-adgroup -filter *

foreach ($group in $groups) {
$naam = $group.name
$members = Get-ADGroupMember -identity $group
write-host “Group: $naam”
write-host “————————————-”
foreach ($member in $members) {
$memnaam = $member.samaccountname
write-host “$naammem”
} | Export-CSV c:\FileName.csv`

CodePudding user response:

Check for typos in variable names (you have one) and that you've closed all parentheses and braces. Even better, don't use variables where not needed:

$groups = get-adgroup -Filter *

# If you save your search as an object you won't need to re-run it multiple times to use the data
Write-Host "Processing groups"
$SearchResult = $Groups | ForEach-Object {
    $GroupName = $_.Name
    # Some simple error trapping
    Try {
        # Writing to host for informational only
        Write-Host "$GroupName..." -NoNewline
        $Members = (Get-ADGroupMember -Identity $_ -ErrorAction Stop).SamAccountName
    }
    Catch {
        $Members = $_
    }
    # Output results as an object
    [pscustomobject]@{
        Group = $GroupName
        Members = $Members
    }
    Write-Host "Done"
}
Write-Host "Processing complete"
# If you want to display it in console
$SearchResult | Format-List
# Or a GridView
$SearchResult | Out-GridView
  • Related