Link to home
Start Free TrialLog in
Avatar of Randall Storm
Randall StormFlag for United States of America

asked on

Powershell Export-CSV only gives one result

Working with Powershell to pull computer name, manufacturer, and model from a list of computers using Get-WMIObject.  The script works in the Powershell window, but I can't get more than one result (the last computer in the list) in the output when piping to Export-CSV.   I understand that Powershell is probably overwriting the information until it reaches the end of the computer list, but don't know how to fix this.  Does someone have a concise solution on how to get this to work?
Here is what I have so far:

$a = Get-Content "C:\temp\Names.txt"
foreach ($i in $a)
    {$i + "`n" + "=========================="; Get-WMIObject Win32_ComputerSystem -computername $i | Select-Object Name, Manufacturer, Model | Export-CSV "C:\temp\MakeModel.csv"}
Avatar of becraig
becraig
Flag of United States of America image

try placing the export-csv outside the foreach loop.


$a = Get-Content "C:\temp\Names.txt"
foreach ($i in $a)
    {$i + "`n" + "=========================="; Get-WMIObject Win32_ComputerSystem -computername $i | Select-Object Name, Manufacturer, Model}  | Export-CSV "C:\temp\MakeModel.csv"

Open in new window

This should also give you what you need based on your current code:

$a = Get-Content "C:\temp\Names.txt"
[array]$Details=$null
foreach ($i in $a)
    {   $details += Get-WMIObject Win32_ComputerSystem -computername $i | Select-Object Name, Manufacturer, Model
} $details | select * | Export-CSV "C:\temp\MakeModel.csv"

Open in new window

Made one edit to remove the type information:

$a = Get-Content "C:\temp\Names.txt"
[array]$Details=$null
foreach ($i in $a)
    {$details += Get-WMIObject Win32_ComputerSystem -computername $i | Select-Object Name, Manufacturer, Model
} $details | select * | Export-CSV "C:\temp\MakeModel.csv" -nti

Open in new window

Avatar of Randall Storm

ASKER

Thanks, becraig, the first solution gives me the following error:
The empty pipe element is not allowed.

The second solution gives the following errors:
Get-WMIObject : Cannot validate argument on parameter 'ComputerName'.  The argument is null or empty
Get-WMMIObject : Not found
Get-WMIObject : The RPC server is unavailable. <Exeption from HRESULT: 0x800706BA>
ASKER CERTIFIED SOLUTION
Avatar of becraig
becraig
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Apologies, becraig, it is working; the errors that I was getting are from a handful of computers in the list that were being queried.  So, I imagine they either have some type of WMI problem or they are offline.
The last one you sent works great.
Thank you very much for your help!
becraig is awesome!
Glad to help.