JRN
JRN

Reputation: 279

Export-CSV not working with my foreach loop

I have a piece of code that I wrote which captures some data and write it to a CSV file. I have written it two way. 1) The first way only gives me the last result rather than all the results almost as if it was over writing itself. 2) The second way gives me an error that says "An Empty Pipe Element Is Not Allowed"

WAY 1)

foreach ($Computer in $CompObjToRM)
{
Get-ADComputer -Identity $Computer | Select Name, DistinguishedName | Export-CSV C:\T2\ServersToRemoveFromAD2.csv -NoTypeInformation
} 

WAY 2)

foreach ($Computer in $CompObjToRM)
{
Get-ADComputer -Identity $Computer | Select Name, DistinguishedName
} | Export-CSV C:\T2\ServersToRemoveFromAD2.csv -NoTypeInformation

What am I doing wrong?

Upvotes: 1

Views: 1983

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174900

Either use the -Append switch parameter with Export-Csv to avoid it overwriting the same file:

foreach ($Computer in $CompObjToRM)
{
    Get-ADComputer -Identity $Computer | Select Name, DistinguishedName | Export-CSV C:\T2\ServersToRemoveFromAD2.csv -Append -NoTypeInformation
} 

or use the ForEach-Object cmdlet (from which you can pipe all the output to Export-Csv)

$CompObjToRM |ForEach-Object {
    Get-ADComputer -Identity $_ | Select Name, DistinguishedName 
} | Export-CSV C:\T2\ServersToRemoveFromAD2.csv -NoTypeInformation

The big difference here is that foreach($thing in $things){} is a builtin semantic feature of the language, whereas ForEach-Object is a cmdlet - a piece of reusable code that supports pipeline input and output.

ForEach-Object can be a bit slower (and behave slightly differently) than the foreach loop, but in most cases, it simply just offers you a greater degree of flexibility in composing your pipeline

Upvotes: 1

Related Questions