I'm trying to export a complete CSV to Excel by using Powershell. I stuck at a point where static column names are used. But this doesn't work if my CSV has generic unknown header names.
Steps to reproduce
Open your PowerShell ISE and copy & paste the following standalone code. Run it with F5
"C:\Windows\system32\WindowsPowerShell\v1.0\powershell_ise.exe"
Get-Process | Export-Csv -Path $env:temp\process.csv -NoTypeInformation
$processes = Import-Csv -Path $env:temp\process.csv 
$Excel = New-Object -ComObject excel.application 
$workbook = $Excel.workbooks.add() 
$i = 1 
foreach($process in $processes) 
{ 
 $excel.cells.item($i,1) = $process.name
 $excel.cells.item($i,2) = $process.vm
 $i++ 
} 
Remove-Item $env:temp\process.csv
$Excel.visible = $true
What it does
- The script will export a list of all active processes as a CSV to your temp folder. This file is only for our example. It could be any CSV with any data
- It reads in the newly created CSV and saves it under the $processesvariable
- It creates a new and empty Excel workbook where we can write data
- It iterates through all rows (?) and writes all values from the nameandvmcolumn to Excel
My questions
- What if I don't know the column headers? (In our example nameandvm). How do I address values where I don't know their header names?
- How do I count how many columns a CSV has? (after reading it with Import-Csv)
I just want to write an entire CSV to Excel with Powershell
 
     
     
     
     
     
     
     
     
    