Powershell – ForEach Loop Export to CSV file

powershell

I am working on creating a script that will output all the computer names and models to an excel file. The code works without the Export-Csv pipe but I can't figure out how to create the excel file. If I take out the loop and use only one computer with the Export-Csv it also works fine.

#Query AD
$Computers = Get-ADComputer -Filter * -searchbase "DC=domain,DC=org"

#loop
foreach ($computer in $Computers) {
$comp=$computer.Name
Get-WmiObject -Class Win32_ComputerSystem -ComputerName $comp | Where-Object {$_.model -like "*G2*"} | Select-Object Name, Model  | Export-Csv "C:\User\xxxxxx\Desktop\8200s.csv" -NoTypeInformation -Encoding UTF8 -Append
}

Best Answer

I suggest you move the Export-CVS out of the loop, and use Foreach-Object so you can use the pipeline.

# Query AD for computers
Get-ADComputer -Filter * -searchbase "DC=domain,DC=org" |
ForEach-Object {
    $comp=$_.Name
    # return name,model for all G2 computers
    Get-WmiObject -Class Win32_ComputerSystem -ComputerName $comp |
        Where-Object {$_.model -like "*G2*"} |
        Select-Object Name, Model
} | Export-Csv "C:\User\xxxxxx\Desktop\8200s.csv" -NoTypeInformation -Encoding UTF8