Export-csv not getting my multi-domain variable

I see successful output for all domains with this query:

ForEach ($domain in ((Get-ADForest).domains)) { Get-ADGroupMember “Domain Admins” -Server $domain -Credential $creds }

…but when I try to pipe it to export-csv, I only get the last domain in the output:

ForEach ($domain in ((Get-ADForest).domains)) {Get-ADGroupMember “Domain Admins” -Server $domain -Credential $creds | Export-Csv C:\temp\compliance\DomainAdmins.csv -NoTypeInformation }

What am I not understanding about my pipeline and how to correct to capture all to a csv?

thanks

export-csv goes outside the loop.

Simplified.

$domains = (Get-ADForest).domains)

$domainadmins = ForEach ($domain in $domains) {Get-ADGroupMember “Domain Admins” -Server $domain -Credential $creds }

$domainadmins | Export-Csv C:\temp\compliance\DomainAdmins_gap.csv -NoTypeInformation

Each time your loop runs, a new CSV is created. You can demonstrate this with a simple bit of code which changes the name of the CSV file each time the loop runs.

$domains = 'domain1','domain2'

foreach ($domain in $domains) {
    
    $domain | Export-Csv "E:\__temp\csv-$domain.csv"

}

In your case, because the name isn’t changed, Export-CSV overwrites file each time the loop runs.

Version 3 added the -append parameter to Export-CSV which will add the data to the file rather than overwriting it.

-Append sounds intriguing but when I try this:

ForEach ($domain in ((Get-ADForest).domains)) {Get-ADGroupMember “Domain Admins” -Server $domain -Credential $creds | Export-Csv C:\temp\compliance\DomainAdmins.csv -NoTypeInformation -Append }

I get error:

Export-Csv : Cannot append CSV content to the following file: C:\temp\compliance\DomainAdmins.csv. The appended object does not have a property that corresponds to the following column: PSShowComputerName 

Yes this works thank you…looking into a one-liner with -Append per below

Even so.

(Get-ADForest).domains) | %{Get-ADGroupMember “Domain Admins” -Server $_ -Credential $creds }| Export-Csv C:\temp\compliance\DomainAdmins_gap.csv -NoTypeInformation

You can use the -Force parameter (doesn’t the full error message say that?) to try and export everything regardless of mismatches. For your scenario, where you’re exporting the same object type each time that should be fine.

have to lose the domains) < ---------- yeah?

Yep, typo in mashing your code together. remove the ) after domains. Understand the pipeline before starting with code golf.

img

Thanks Dan

Thank you for the demo script Matt…I see that now.