7

When running the following code:

  $txt = Get-Content file1.txt

    $a = @"
     -- file start --
     $txt
     -- file end --
    "@

   $a

All new lines are removed from the file's contents, but just running

$txt

prints out the file without stripping the new lines.

Any idea how to get it to work as desired using the here-string?

Thanks!

2 Answers 2

14

If you put an array in a string it will be expanded with $OFS (or a space if $OFS is $null) between the items. You can see the same effect with either

"$txt"
''+$txt

and a few others. You can set $OFS="`r`n" which would change the space with which they are joined to a line break.

You could also change the Get-Content at the start to either

$txt = Get-Content file1.txt | Out-String
$txt = [IO.File]::ReadAllText((Join-Path $pwd file1.txt))
1
  • Thanks for your answer, that explained a lot about what's going on.
    – Bob Smith
    Oct 25, 2012 at 19:23
11

Pipe $txt to Out-String inside a sub-expression.

$a = @"
    -- file start --
    $($txt | Out-String)
    -- file end --
"@
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.