I have a text file with hundreds of rows. Data fields and values separated by a colon and one empty line separating each data set. It looks something like this...
ico
The simplest approach would be to split your data at 2 consecutive newlines and convert the data chunks into hashtables via ConvertFrom-StringData (you must also replace :
with =
for that to work). The hashtables can then be converted to custom objects and exported to a CSV.
$data = Get-Content 'C:\path\to\input.txt' -Raw
$data -replace ':', '=' -split '\r?\n\r?\n' | ForEach-Object {
[PSCustomObject]($_ | ConvertFrom-StringData)
} | Export-Csv 'C:\path\to\output.csv' -NoType
Note that the above requires PowerShell v3 or newer. For older PowerShell versions you need to adjust the code as below:
$data = Get-Content 'C:\path\to\input.txt' | Out-String
$data -replace ':', '=' -split '\r?\n\r?\n' | ForEach-Object {
$prop = $_ | ConvertFrom-StringData
New-Object -Type PSObject -Property $prop
} | Export-Csv 'C:\path\to\output.csv' -NoType
If you want the fields of the CSV in a particular order you can put a Select-Object
between the ForEach-Object
and Export-Csv
:
... | ForEach-Object {
...
} | Select-Object icon, temperatureHigh, ... | Export-Csv ...
Import-Csv
expects the input data organized as one dataset per row. It cannot be used for blocks of key:value pairs like your input data has.
ConvertTo-Csv
requires the same preparation as Export-Csv
in the sample code above. The only difference is that the output isn't written to a file.