i have to export all domain groups with their members to csv. So each group has to get their own csv. in this csv has to be all group members.
I think i know where the problem is: $group value is @{name=xyz} not xyz. Probably thats why ADGroupMember -Identity isnt matching.
$groups = (Get-ADGroup -filter {GroupScope -eq "DomainLocal"} |Select-Object name)
foreach ($group in $groups) {
Add-Content -Path ("C:\" $group) -Value (Get-ADGroupMember -Identity $group)
}
edit: code solved below. i would need help with adding users to each csv file. dunno how to look for them.
CodePudding user response:
You need to modify the first line like that
$groups = (Get-ADGroup -filter {GroupScope -eq "DomainLocal"}).name
CodePudding user response:
As commented, you need to get the string value of the property called Name
, not an object that holds that property with value Name.
Then there is the problem of how you create the output file name, AND cmdlets Add-Content
, Set-Content
etc. are not meant to write CSV files. For that PowerShell has Export-Csv
where you feed it the objects returned from Get-ADGroupMember
in this case:
$groups = Get-ADGroup -Filter "GroupScope -eq 'DomainLocal'" | Select-Object -ExpandProperty Name
foreach ($group in $groups) {
# construct the output path for the csv file
$csvOut = Join-Path -Path "C:\19158" -ChildPath ('{0}.csv' -f $group)
# use Export-Csv to create a correct CSV file
Get-ADGroupMember -Identity $group | Export-Csv -Path $csvOut -UseCulture -NoTypeInformation
}
An alternative would be to not use Select-Object at all, but loop through the objects returned from Get-ADGroup
and use the $_
Automatic variable
Get-ADGroup -Filter "GroupScope -eq 'DomainLocal'" | ForEach-Object {
# construct the output path for the csv file
$csvOut = Join-Path -Path "C:\19158" -ChildPath ('{0}.csv' -f $_.Name)
# use Export-Csv to create a correct CSV file
$_ | Get-ADGroupMember | Export-Csv -Path $csvOut -UseCulture -NoTypeInformation
}