H
H
hixr0k2020-10-20 15:22:38
PowerShell
hixr0k, 2020-10-20 15:22:38

Why in Powershell when exporting to csv fills one line?

I made a file where I entered the display name from AD 10 accounts, at the output I want to get a file where the display name and login are combined.
When exporting to csv, only one line is filled, I can’t figure out how to make the lines fill in the loop.

$users = Get-Content C:\temp\users.csv
ForEach ($user in $users ) {
    Get-ADUser  -Filter "Name -eq '$user'"| Select-Object name, samaccountname | export-csv C:\1.csv -NoType -UseCulture -Encoding UTF8
}

If someone can suggest a more elegant solution, I would be grateful.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2020-10-20
@hixr0k

Don't do an Export- in the middle of a loop. it should be outside
, you can use a pipeline instead of a cycle

Get-Content C:\temp\users.csv |
  Get-ADUser |
  Select-Object name, samaccountname |
  export-csv C:\1.csv -NoType -UseCulture -Encoding UTF8

A
Alexey Dmitriev, 2020-10-21
@SignFinder

A more elegant solution was suggested above.
And in your case, you need to use the additional parameter -Append for Export-CSV and delete / reset the file at the beginning of the script.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question