Home > Blockchain >  Backup multiple groups with their members
Backup multiple groups with their members

Time:12-24

I would like to make a backup of all the groups -like DEP_Fin_* (I have about 30 groups). I would like to generate an excel or csv backup file for each groups. The name of each backup files must be the ADGroup name. When I run the script I only have one backup file... can you help me with this?

$Path = "C:\Temp\$($group.Name).xlsx"
$adgroup = Get-ADGroup -filter {Name -like "DEP_Fin_*"} -Properties Name


$result = foreach($group in $ADGroup) {

Get-ADGroupMember -Identity $group.Name | Where-Object {
        $_.objectclass -eq "user"
    } | Select DisplayName, SamAccountName
     }


$Result | Export-Excel -Path $Path

CodePudding user response:

Because you are gathering all info in the variable result, you will only have one output file.

Also, the top line of your code does not create a valid file path, because at that time $group.Name is undefined.

Try

$path = 'C:\Temp'
$adGroups = Get-ADGroup -Filter "Name -like 'DEP_Fin_*'"

foreach($group in $adGroups) {
    $group | Get-ADGroupMember | Where-Object { $_.objectClass -eq 'user' } |
             Select-Object DisplayName, SamAccountName |
             # export this group here as CSV or by using Export-Excel
             Export-Csv -Path (Join-Path -Path $path -ChildPath ('{0}.csv' -f $group.Name)) -NoTypeInformation -UseCulture
             # or by using Export-Excel
             # Export-Excel -Path $Path (Join-Path -Path $path -ChildPath ('{0}.xlsx' -f $group.Name))
}
  • Related