export to csv the results of a foreach

I have this script, but returns me an empty csv why?

$users = import-csv "C:\Temp\script\usersinsim.csv" -Header user
ForEach ($user in $users)
{
get-qaduser -lastname $user.user -SizeLimit 0 | select logonname | Export-Csv -Path "C:\Temp\script\output.csv"
}

March 26th, 2014 2:24pm

What you're doing is : ForEach user, get the logonname, write that to a new csv file.

Try this:

$users = import-csv "C:\Temp\script\usersinsim.csv" -Header user
$Logonames = $users | ForEach  {
 get-qaduser -lastname $_.user -SizeLimit 0 | select logonname
 }

$Logonames | Export-Csv -Path "C:\Temp\script\output.csv" -NoTypeInformation


Or like this:

$users = import-csv "C:\Temp\script\usersinsim.csv" -Header user
Clear-Content -Path "C:\Temp\script\output.csv" -ErrorAction SilentlyContinue
 ForEach ($user in $users)
 {
    (get-qaduser -lastname $user.user -SizeLimit 0).logonname | Add-Content -Path "C:\Temp\script\output.csv"
 }

Or a one liner ;-)

(Get-Content "C:\Temp\script\usersinsim.csv").Trim() | Get-qaduser -lastname $_ -SizeLimit 0 | select logonname | Export-Csv -Path "C:\Temp\script\output.csv" -NoTypeInformation





  • Edited by gaff-jakobs Wednesday, March 26, 2014 5:31 PM
  • Marked as answer by Cesar Mattheus Thursday, March 27, 2014 8:22 AM
Free Windows Admin Tool Kit Click here and download it now
March 26th, 2014 7:30pm

Fantastic!! thanks a lot! it works perfectly!!

March 27th, 2014 11:25am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics