diff --git a/powershell/backup-groupmembers.ps1 b/powershell/backup-groupmembers.ps1 index 5006695..f8195c9 100644 --- a/powershell/backup-groupmembers.ps1 +++ b/powershell/backup-groupmembers.ps1 @@ -6,26 +6,36 @@ $groups = @("", "") $csv_file = "backup_$(Get-Date -Format 'yyyy-MM-dd_HH-mm-ss').csv" -try { - foreach ($group in $groups) { - $ad_group = Get-ADGroup -Filter 'Name -eq $group -and GroupScope -eq "DomainLocal" -and GroupCategory -eq "Security"' -Server $server -Properties Member -ErrorAction Stop - $csv_export_table = @() - $ad_group.Member | ForEach-Object { - try { - $ad_user = Get-ADUser -Identity $_ -Properties * -Server $server -ErrorAction Stop - $csv_export_table += [PSCustomObject]@{ - Group = $group - MemberEmail = $ad_user.SamAccountName - MemberDistinguishedName = $ad_user.DistinguishedName +$csv_export_table = @() + +foreach ($group in $groups) { + try { + $ad_group = Get-ADGroup -Filter 'Name -eq $group -and GroupScope -eq "DomainLocal" -and GroupCategory -eq "Security"' -Server $server -Properties Member -ErrorAction Stop + + if ($ad_group.Member) { + $ad_group.Member | ForEach-Object { + try { + $ad_user = Get-ADUser -Identity $_ -Properties * -Server $server -ErrorAction Stop + $csv_export_table += [PSCustomObject]@{ + Group = $group + MemberEmail = $ad_user.SamAccountName + MemberDistinguishedName = $ad_user.DistinguishedName + } + } catch { + Write-Warning "User $_ not found in group $group - skipping..." } - } catch { - Write-Error "User $group not found and skipped..." } + } else { + Write-Warning "Group $group has no members" } + } catch { + Write-Warning "Group $group not found - skipping..." } -} catch { - Write-Error "Group $group not found" - exit 1 } -$csv_export_table | Export-Csv -Path $csv_file -NoTypeInformation \ No newline at end of file +if ($csv_export_table.Count -gt 0) { + $csv_export_table | Export-Csv -Path $csv_file -NoTypeInformation + Write-Host "Backup completed successfully. Exported $($csv_export_table.Count) members to $csv_file" +} else { + Write-Warning "No members found to export" +} \ No newline at end of file