PowerShell text file and csv read / write
PowerShell text file and csv read / write
This article is a summary of examples for creating and reading text and CSV files in PowerShell.
Create text file
'Name','Nummer' | out-file c:\temp\text.txt
Create CSV file
'Name,Nummer' | out-file c:\temp\text.csv
Attach CSV file content
'Walter,007' | out-file c:\temp\text.csv -Append
Read text file
Get-Content c:\temp\text.txt
CSV file from an object
By means of Export-CSV
objects can be exported to a CSV file:
get-counter | Export-CSV test.csv -append
"append" adds values to an existing .csv file and creates a .csv file if none exists
Possibly useful additional parameters:
-Encoding UTF8
... encodes the file in UTF8, may be needed in case of problems with umlauts
-Delimiter ";"
... Instead of "," as separator ";" is used
-NoTypeInformation -Force
... disables the first line in the CSV where PowerShell stores information about the file.
Read CSV file
Import-csv c:\temp\text.csv
Import-csv c:\temp\text.csv | select -ExpandProperty Nummer
read out certain entries from the CSV file
Import-csv c:\temp\text.csv | Where-Object {$_.Name -eq 'Walter'}
see also: PowerShell Syntax: compare and nest
read specific values from the CSV file
$(Import-csv c:\temp\text.csv | Where-Object {$_.Name -eq 'Walter'}).Nummer
({{pro_count}})
Rate Post:{{percentage}} % positive
({{con_count}})