New line in body of an email when output is from an array

Andrew Rose 1 Reputation point
2021-11-24T10:17:15.9+00:00

I load some information in from a file which is of the format

User1
User2
etc

using $Input = Get-Content "StaticUsers.txt"

At the end of my script I send an email with the body being sent to a number of users using

$body = "$Input" + "rn"

The issue is that the received email shows the list as the following

User1 User2 etc

instead of each item on a new line. How can I achieve this?

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 45,091 Reputation points
    2021-11-24T20:01:32.953+00:00

    Use the "-join" operator:

    $Input = 1,2,3,4
    $body = ($input -join [Environment]::NewLine) + [Environment]::NewLine
    

    You can substitute "rn" for "[Environment]::NewLine" if you like.

    0 comments No comments

  2. Limitless Technology 39,371 Reputation points
    2021-11-26T08:40:59.807+00:00

    Hello

    Thank you for your question and reaching out.

    The PowerShell newline indicator is n, and can only be used in double quotes. Single quotes will print the actual "n".

    For Example :
    $body = "first line" + "`n" + "second line"

    Also, One solution would be to use <br /> to break lines and specify the switch -BodyAsHtml so that body would be treated as html and email client would display it correctly, alternatie approach would be to use `n for line breaks and keep body as text.


    --If the reply is helpful, please Upvote and Accept as answer--