# Import the required module try { Import-Module ActiveDirectory -ErrorAction Stop } catch { Write-Error "Failed to import ActiveDirectory module. Error: $_" return } # Create an empty array to hold the data $results = @() # Get all AD groups try { $groups = Get-ADGroup -Filter * -ErrorAction Stop } catch { Write-Error "Failed to get AD groups. Error: $_" return } # Initialize a variable to store the previous group name $previousGroup = "" # Loop over each group foreach ($group in $groups) { # Skip the "IIS_IUSRS" group if ($group.Name -eq "IIS_IUSRS") { continue } # Get the members of the current group try { $members = Get-ADGroupMember -Identity $group -ErrorAction Stop | Where-Object {$_.objectClass -eq 'user'} } catch { Write-Error "Failed to get members for group $($group.Name). Error: $_" continue } # Loop over each member foreach ($member in $members) { # Check if the account is enabled $user = Get-ADUser -Identity $member.SamAccountName -Properties Enabled, Description if ($user.Enabled -eq $true) { # Create a new object to hold the group and member data $result = New-Object PSObject -Property @{ "Group Name" = $group.Name "Member" = $user.SamAccountName "Description" = $user.Description } # Add a space if the current group is different from the previous group if ($group.Name -ne $previousGroup) { $results += [PSCustomObject]@{ "Group Name" = "" "Member" = "" "Description" = "" } } # Add the object to the results array $results += $result # Update the previous group variable $previousGroup = $group.Name } } } # Set the output directory and filename $outputDir = "C:\ADAudit" $outputFile = Join-Path -Path $outputDir -ChildPath "S. ADGroupsAndMembers.csv" # Create the directory if it doesn't exist if (!(Test-Path -Path $outputDir)) { New-Item -ItemType Directory -Path $outputDir | Out-Null } # Export the results to a CSV file try { $results | Export-Csv -Path $outputFile -NoTypeInformation -ErrorAction Stop } catch { Write-Error "Failed to export results to CSV. Error: $_" }