1

I'm trying to add a specific user to a csv file. The file must have Name, Username, Email and Date as headers and when a user is added the specific variables are placed in the correct column. Here is what I have so far:

  Add-content -path C:\...\file.csv -value '"name","username","email","date"'
  $user = @($name,$username,$email,$date)
  Add-content -path C:\...\file.csv -value $user

(The variable name, email, username and date are defined previously and are strings)

When I run the command

 import-csv -path C:\...\file.csv

It returns the variables defined in the column Name instead of each variable being placed in it's specific header. Why is this happening?

1
  • Most of the time it's much easier to use Export-CSV (and Import-CSV) than creating the file with Add-Content. Could you show us the first 2-3 rows of the file? Commented Feb 24, 2021 at 14:10

1 Answer 1

2
 New-Object -TypeName PSCustomObject -Property @{
    Name=$name
    Username=$username
    Email=$email
    Date=$date
 }|Export-Csv -path C:\...\file.csv -NoTypeInformation -Append
Sign up to request clarification or add additional context in comments.

1 Comment

Jep that's better ;) If you take a look at the object that Import-Csv creates, you can see that it is an array of [PSCustomObject]. And that is what Export-Csv handles best too. The easiest way to create an array of [PSCustomObject] is with ... | Select-Object. That is if you don't need to create it from scratch...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.