List all groups with groupmembers

Recently we needed a script that could list all groups with all group members – we struggled a bit with the layout of the file. But here it is

-Searchbase should be replaced with your own distinguished name

$Groups = Get-ADGroup  -Properties * -Filter * -SearchBase "DC=domain,DC=dk"
[string]$msg = ""
Foreach($G In $Groups) {
$msg+=$G.Name + "`n"

$msg+="------------------------------" + "`n"

foreach ($Member in $G.Members) {

$msg+=$($Member -replace '^CN=|,.*$') +"`n"

}

$msg+="`n"

}

$msg | out-file C:\Temp\GroupMembers.txt -Encoding utf8