DevOps | Scripts | Automation

Powershell

How to work with CSV file in PowerShell – Part I?

CSV file is the essential part of the PowerShell. Be it to store the output or to process the input CSV file, it makes PowerShell easier to process the data because it has the header structure and like the Hashtable we can work on multiple objects and iterate and filter through various items.

A) Create CSV with Array and Headers.

There are multiple methods to create and store values inside the CSV file. First, we will check how we can create a CSV file manually using an array and headers.

To create headers using an empty array,

In this method, we will first create an empty array and create headers for the CSV file. Later, we will export this CSV file using the Export-CSV command, and to use we will have to use the Import-Csv command.

$csvfile = {} | Select "EmpName","EMPID","City","Designation"

Once we check the output, the headers should be created.

Now we have to save the above header information in the CSV file, so we will use the Export-CSV command with the FileName and with –NoTypeInformation so that the CSV information will not be added to the CSV file.

$csvfile | Export-Csv C:\Temp\Employeedata.csv -NoTypeInformation

With the above command, the CSV file will be created named Employeedata.csv inside the C:\temp folder.

To import the created CSV file, we can use the Import-CSV command. For example,

Import-Csv -Path C:\Temp\Employeedata.csv

B) Create CSV with Export-CSV command.

If you have the table output and you want to store the output in a CSV file, the easy way is to use the Export-CSV command.

Get-Process | Export-Csv C:\Temp\processes.csv -NoTypeInformation

To create the csv with the selected headers,

get-process | Select Name, Id, WorkingSet, CPU | Export-Csv C:\Temp\Processinfor.csv -NoTypeInformation

C) Create a CSV file with PSCustomObject.

We can also use the PSCustomObject and Export-CSV command to retrieve the output to the CSV files. This method is the best when you want to store the multiple commands output to the CSV file.

$bios = Get-CimInstance Win32_BIOs
$comp = Get-CimInstance Win32_ComputerSystem

$output = [PSCustomObject]@{
             SystemName = $comp.Name
             Domain = $comp.Domain
             Manufacturer = $bios.Manufacturer
             BIOSName = $bios.Name
             BIOSVersion = $bios.Version  
          }


$output | Export-Csv C:\Temp\SystemInfo.csv -NoTypeInformation

In the above example, we have stored the output in the PSCustomObject and then the output is exported to the CSV file.