Home > Software engineering >  How do I replace a string in Powershell with a Multi-Line String?
How do I replace a string in Powershell with a Multi-Line String?

Time:02-10

I am trying to create a report in a rich text format in powershell. I have a space for a list of templates, denoted by the text %TEMPLATES%, which I am trying to replace with a list of items in a directory. However, whilst I can add newlines to the list of items to separate them (and this prints OK in the console window) when I replace them in the rtf document the newlines are not present and the items are all joined with no spacing. I can't figure out why this -replace wouldn't work. See the example code below:

$statusRecordTemplate = 'StatusRecord.rtf'

$templates = (Get-ChildItem $templatesPath) | Join-String -Separator "`r`n"

$content = Get-Content $statusRecordTemplate -Raw

$content = $content -replace '%TEMPLATES%' , $templates

Set-Content  -Path 'C:\temp\testout.rtf' -Value $content

CodePudding user response:

Newlines in RTF are not significant. You have to use the paragraph tag (\par) instead.

$templates = (Get-ChildItem $templatesPath) | Join-String -Separator '\par '

Make sure to include a space after the tag, as in my sample. This is necessary when a tag is followed by literal text.

Additionally you have to escape control characters in the literal text and properly encode any non-ASCII characters. See this Q&A for further information.

  • Related