Link to home
Start Free TrialLog in
Avatar of CES
CES

asked on

PowerShell Output only returns last item in list

I am trying to import a list of server names from a .csv file, grab the AD Computer name and either pipe that list to a new command or export it to CSV.

I am finding that my import seems to work, however when I pipe that to my next command (I've tried foreach and ForEach-Object) my results only show the last server in the list. Here is the script I am writing:

import-module activedirectory
$serverlist = Import-Csv \\path\ADComputers.csv
$hosts=@()
    foreach($sever in $serverlist)
    {
    $hosts +=Get-ADComputer $server.Name
    }
   
 $hosts | Export-Csv C:\ps\hosts.csv

So say my imported CSV has serverA - serverZ, when I run the script I get 26 lines saying "serverZ."  This tells me that the foreach is running through all the servers but is overwriting itself somewhere.  I just can't figure out where.

Any advice?
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

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
import-module activedirectory
$serverlist = Import-Csv "\\path\ADComputers.csv"
$hosts=foreach($server in $serverlist) { Get-ADComputer -Identity $server.Name }
$hosts | Export-Csv C:\ps\hosts.csv

Open in new window

Avatar of CES
CES

ASKER

Well that's embarrassing... Thanks for the second set of eyes! Working as expected now.
You have no idea how often I discovered an error only after/while explaining to somebody else what I was trying to do, and that is was failing ...

One more thing: you might want to add "-NoTypeInformation" to your Export-Csv, which will remove the type definition at the beginning of the file.

And now that you've got it running "your" way ("programmer" style, with lots of intermediate variables), here's how to do it the "Powershell way", using the pipeline (no judgment, takes some getting used to):
Import-Module ActiveDirectory
Import-Csv \\path\ADComputers.csv | ForEach-Object {Get-ADComputer -Identity $_.Name} | Export-Csv -NoTypeInformation -Path C:\ps\hosts.csv

Open in new window