output csv file is overwritten when using loop in powershell for input

Hi,

I am running this script which is gathering the info for all users from input file but only the last users data is exported to the output file.

import-csv .\users.txt | foreach-object{
$users=get-ADUser -identity $_.samaccountname -properties DistinguishedName, employeeID, Enabled, Name, 

LastLogontimestamp | select DistinguishedName, EmployeeID, Enabled, Name, @{N='LastLogontimestamp'; E={
[DateTime]::FromFileTime($_.LastLogontimestamp)
     } 
   }
}
$users |export-csv c:\ad\users.csv

Please help me asap!!

Regards..

February 11th, 2014 12:03am

Hi,

Quick fix: change $users= to $users+=.

Longer but cleaner fix: don't create a $users array, just run everything directly through the pipeline.

Free Windows Admin Tool Kit Click here and download it now
February 11th, 2014 12:12am

Hi Mike,

Thanks, can you please show me the command modified exactly. Consider me Naive in powershell :)

Thanks!!

February 11th, 2014 12:25am

Hi,

Give this a try:

Import-Csv .\users.csv | ForEach {

    Get-ADUser $_.SamAccountName -Properties EmployeeID,LastLogonDate |
        Select DistinguishedName,EmployeeID,Enabled,Name,LastLogonDate

} | Export-Csv .\userDetails.csv -NoTypeInformation

This assumes you have an input CSV file with a header of SamAccountName with usernames underneath.

Free Windows Admin Tool Kit Click here and download it now
February 12th, 2014 7:14am

Cheers, you're very welcome.
February 12th, 2014 10:15am

Thanks Mike, That worked!!

Cheers!!

Free Windows Admin Tool Kit Click here and download it now
February 12th, 2014 10:27am

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

Other recent topics Other recent topics