One of the best and easiest ways to put data into an easy-to-read format is with a CSV (comma-separated values ) file. The CSV file will have a line of headers to indicate column name and subsequent values for each column. The structured data is required for positioning in the CSV file, to achieve the PowerShell has few option for structured data. Since a CSV file is just like a text file, it can loosely be created with Powershell’s Add-Content cmdlet. Here i had explained how to Export CSV file with Array with help of simple Add-Content cmdle.
We can use both Add-Content OR Export-Csv to create and write the CSV files, the best way is use Export-Csv (if we created a structured data/object) else we can use Add-Content cmdlet . The Add-Content does not negatively understand a CSV file, it would still be able to read one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
############################################################ #Project : Read Array values and generate CSV file #Developer : Thiyagu S (dotnet-helpers.com) #Tools : PowerShell 5.1.15063.1155 #E-Mail : mail2thiyaguji@gmail.com ############################################################ #Declared the File path location with the CSV format. $FilePathLocation = "C:\PowerShell\EmployeeDetails.csv" #Declared the Array $Empdetails =@(); $empCount = 3; #Declared the Column names $columnName = '"EmpName","EMPID","EMPemail","EMPpin"' #Add the column tile to the Excel Add-Content -Path $FilePathLocation -Value $columnName #Loop will get user input for 3 time for ($loopindex=0; $loopindex -lt $empCount; $loopindex++) { #Getting the User Input from the console $Empdetails += Read-Host " Enter EMPName,EMPID,EMPemail,EMPpin by comma separator" } #looping the Emp details to print in the excel cell $Empdetails | foreach { Add-Content -Path $FilePathLocation -Value $_ } |
Output:
Export CSV file with Array
What do you think?
I hope you have an idea of How To Read Array values and generate CSV file with PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.