How to create a CSV file manually in PowerShell?


There are few methods to create a CSV file in the PowerShell, but we will use the best easy method to create it.

First, to create a CSV file in PowerShell, we need to create headers for it. But before it, we need output file name along with its path.

$outfile = "C:\temp\Outfile.csv"

Here we have given output file name Outfile.csv in the path C:\temp.

Now we will create headers,

$newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile

Here, we have created a CSV file and exported a file to the newly created file.

We will now import this file to check if the headers are created.

Import-Csv $outfile

Output

EMP_Name EMP_ID CITY
-------- ------ ----

So, in the above output, we can see the headers are created.

Now we need to insert the data inside the CSV file, for that we first import CSV file into a variable and then we will insert data.

Example

$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "Charles"
$csvfile.EMP_ID = "2000"
$csvfile.CITY = "New York"

Output

Check the output of the above-inserted data.

PS C:\WINDOWS\system32> $csvfile
EMP_Name    EMP_ID    CITY
--------    ------    ----
Charles     2000      New York

Overall commands to create a script −

$outfile = "C:\temp\Outfile.csv"
$newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile
$csvfile = Import-Csv $outfile
$csvfile.Emp_Name = "Charles"
$csvfile.EMP_ID = "2000"
$csvfile.CITY = "New York"

This output is stored into the variable, to store this output into the created CSV file, you need to export CSV file to the output file again as shown in the below example.

Example

$csvfile | Export-CSV $outfile

Output

Import-Csv $outfile

Output

EMP_Name    EMP_ID       CITY
--------    ------       ----
Charles     2000 New     York

Updated on: 26-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements