Alexander Seidl
Alexander Seidl

Reputation: 128

Powershell: Format output of Import-Csv Records in a specific way

id like to format the output of CSV Records in a specific way.

Lets say, i have a csv file with these records:

Field1,Field2
blah,blah
bluh,bluh

Now, what i want to achieve is an output (into console or file) with this format

('blah','blah')
('bluh','bluh')

This [1] does not work! Powershell simply writes nothing into out.txt.

[1]

Import-Csv .\test.csv | Select-Object Field1,Field2 | ForEach-Object {Write-Host "('"$_.Field1"', '"$_.Field2"')"} > .\out.txt

Upvotes: 0

Views: 883

Answers (2)

JohnLBevan
JohnLBevan

Reputation: 24430

Use the format operator:

import-csv .\test.csv | %{ "({0},{1})" -f $_.Field1, $_.Field2; }

To output to file, simply pipe the output there; i.e.

import-csv .\test.csv | %{ "({0},{1})" -f $_.Field1, $_.Field2; } | out-file .\out.txt

For more info on the format operator: http://ss64.com/ps/syntax-f-operator.html

Upvotes: 3

walid toumi
walid toumi

Reputation: 2272

Try this if work

...{Write-output "('$($_.Field1)', '$($_.Field2)')"} > .\out.txt

Dont use write-host

Upvotes: 2

Related Questions