Author Posts

December 12, 2016 at 7:26 pm

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

December 12, 2016 at 7:29 pm

export-csv goes outside the loop.

December 12, 2016 at 7:32 pm

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

December 12, 2016 at 7:37 pm

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.

December 12, 2016 at 8:16 pm

-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 

December 12, 2016 at 8:16 pm

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

December 12, 2016 at 8:40 pm

Even so.

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

December 12, 2016 at 9:22 pm

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.

December 12, 2016 at 9:29 pm

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

December 13, 2016 at 12:16 am

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

Untitledimg

December 13, 2016 at 8:51 pm

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