Checking PS code to write object array to CSV file please.

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 7 years and 4 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
grathal
Posts: 98
Last visit: Tue Nov 27, 2018 4:16 am

Checking PS code to write object array to CSV file please.

Post by grathal »

Hi there,

I'm using Import-Csv to read an addressbook in CSV text format, one entry per line, then I'm do some validation on each entry and write it back out as a CSV file using the following PowerShell line (I also need to remove the default double-quoting as well as the header line) :

$ValidData | Select-Object Lastname, Firstname, Email, Phone, Office, Department | ConvertTo-Csv -Delimiter ';' -NoTypeInformation | %{ $_ -replace '"', "" } | Select-Object -Skip 1 | Out-File -FilePath $OutputFileEC -Encoding Default

The speed and perfomance are acceptable but the PowerShell looks very long to me. Is there a (much) better way to do the same thing please or is it good enough?

Thanks,

- Alan.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Checking PS code to write object array to CSV file please.

Post by jvierra »

No that is about the simplest way.

You could also just format the rows to a file:

Sometimes clarity is more useful than simplicity.
  1. $ValidData |
  2.     ForEach-Object{
  3.         '{0},{1},{2},{3},{4},{5}' -f $_.Lastname, $_.Firstname, $_.Email, $_.Phone, $_.Office, $_.Department
  4.     } | Out-File $OutputFileEC
User avatar
grathal
Posts: 98
Last visit: Tue Nov 27, 2018 4:16 am

Re: Checking PS code to write object array to CSV file please.

Post by grathal »

Thank you, that looks very elegant.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Checking PS code to write object array to CSV file please.

Post by jvierra »

Glad it works for you.
This topic is 7 years and 4 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked