0

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
1
  • 1
    Instead of Write-Host you should use Write-Output if you intend the text to be output. Commented Oct 11, 2014 at 18:09

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The key here is not the format operator, but that fact that he removes write-host so it sends the object(string) to the pipeline(he could also use Write-Output, which does the same). Write-Host is for interactive messages only, they are not sent as objects that can be piped into another command or written to a file.
2

Try this if work

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

Dont use write-host

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.