Matthias Güntert
Matthias Güntert

Reputation: 4638

How to automatically apply a line break to a long string

I am trying to embbed a base64 encoded PDF into my PowerShell script. This works so far without an issue. However this results in one long line within my script.

So the question is:

How can I convert my very long base64 string into a string containing line breaks with backticks without having to manually add them?

This one...

$test = "asdfghjklmasdfghjklmasdfghjklmasdfghjklmasdfghjklm"

Should become this one...

$test = "asdfghjklm`
asdfghjklm`
asdfghjklm`
asdfghjklm`
asdfghjklm"

Upvotes: 0

Views: 1530

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Why the backticks? Inserting newlines into a base64-encoded string should not make any difference.

PS C:\> $s = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
PS C:\> $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($s))
PS C:\> $b64
TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=
PS C:\> $b64w = $b64 -replace '.{10}', "`$&`n"
PS C:\> $b64w
TG9yZW0gaX
BzdW0gZG9s
b3Igc2l0IG
FtZXQsIGNv
bnNlY3RldH
VyIGFkaXBp
c2NpbmcgZW
xpdC4=
PS C:\> [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64w))
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
PS C:\> [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64))
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Upvotes: 1

Related Questions