Search code examples
powershellmultilinestring-literals

Powershell to set multi-line legalnoticetext in registry - Windows 10


Ok, been searching for the answer to this for hours and I can't believe I am not finding a clear cut solution. How do you enter multi-line text into "legalnoticetext" via script?

Key - Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

I have this command for powershell

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "legalnoticetext" -Value "*** Authorized Access Only *** Second line of message..."

I have a multi paragraph message that needs to be added. I have tried multiple things, like \n, but am not stumbling on solution. I know it is easy to do this via the local GPO editor but I need to script it to run on a hundred remote machines.

Any help?


Solution

    • To embed a newline (line break) inside a "..." string literal, i.e. inside an expandable (interpolating) string, use `n (or `r`n for Windows-format CRLF newlines).

      • See about_Special_Characters.

      • Example:

        # Note the use of `n
        Set-ItemProperty 'HKLM:\SOFTWARE\...' `
          -Name legalnoticetext `
          -Value "*** Authorized Access Only ***`nSecond line of message..."
        
      • Note: Use of "..." implies that $-prefixed tokens in the string are subject to expansion (string interpolation), unless the $ characters are escaped with `. If you prefer to use a verbatim string ('...'), you can use its here-string variant, as shown below.

    • Alternatively, use a here-string, which allows you to use literal newlines in string literals.

      • Note: In here-strings, the newline format - LF-only (Unix-format) vs. CRLF (Windows-format) - is implied by the newline format of the enclosing script file.

      • Example:

        # Note the use of @'<newline>...<newline>'@
        Set-ItemProperty 'HKLM:\SOFTWARE\...' `
          -Name legalnoticetext `
          -Value @'
        *** Authorized Access Only ***
        Second line of message...
        '@
        
        • Important:
          • The opening delimiter, @' (or @" in expandable (interpolating) here-strings), must either be at the very end of the line or only be followed by whitespace.
          • The closing delimiter, '@ (or "@ in expandable (interpolating) here-strings) must be at the very start of the line.
          • No leading whitespace is stripped from the content of here-strings.