Many times we need to export data in CSV files and read
specific information from it. Best example would be log files which contain
lots of data but we want to read some specific information from it like Errors,
Warnings etc.
In this small article I’ll explain how we can export data to
csv files using Export-CSV cmdlets and import csv files and read specific
information from it using Import-CSV cmdlets.
Export-Csv
This command will export data into csv file. In below
example I exported latest 100 Application event log entries to logs.csv file.
Get-EventLog Application -Newest 100 | Export-Csv logs.csv
You can verify data inside csv file using below command.
Get-Content logs.csv
Import-Csv
This command will import data from CSV file. You can specify
delimiter and headers to load only selected columns from csv file.
Script –
#specify path
$path = "C:\PowerShell\logs.csv"
#import csv file and specify specific columns you want to
import using -Header
$file = Import-Csv $path
-Delimiter ","
#$file
#loop all the rows in file
foreach ($row
in $file)
{
#condition to
read only Errors
if ($row.EntryType
-like '*Error*')
{
Write-Host
"---------------------------------------------"
Write-Host
$row.EntryType
Write-Host
$row.TimeGenerated
Write-Host
$row.Message
Write-Host
"---------------------------------------------"
}
}
Output –
You can download code from Gist.
Thank you for reading this article. Please leave your
feedback in comments below.
Reference –
See Also –