Learn about Windows PowerShell
Summary: Here is the answer to Problem 2 in Windows PowerShell Mini-Scripting Games 2014.
Microsoft Scripting Guy, Ed Wilson, is here. Problem 2 could be a bear to solve. After all, it involves text manipulation. Last week, I posted the complete Problem 2 description and task outline.
You have a CSV file that contains five columns. It comes from the HR department and it contains information that you do not need. You only need to work with three of the columns.
As I said, it could be a bear to solve this problem, unless you remember that when imported, a CSV file produces objects. Therefore, all I need to do is to use the Select-Object cmdlet to select the columns I need, and export the file back to a CSV file. Here is a simple CSV file that I can use:
Let's say that I need the Fname, Lname, and Email from this file. All I need to do is to import the CSV file, select the three fields I want, and then export the file back out. Here is how I do it:
Import-Csv C:\DataIn\p2.csv |
Select-Object Fname, Lname, Email |
Export-Csv C:\DataOut\p2Groomed.csv -Append -NoTypeInformation
The groomed data is shown here:
That is all there is to solving Problem 2. Mini-Scripting Games Answer Week will continue tomorrow when I will talk about the answer to Problem 3.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at email@example.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
import-csv C:\Users\test\Desktop\test.csv -Header @("col1", "col2","col3") | ConvertTo-Csv | select -Skip 2 | Out-File C:\Users\test\Desktop\test1.csv
With this I take first 3 column of any CSV and output it back to CSV without losing header Information
I over-thinking a little bit ><!