How to fix outout for a string array while sending email using Powershell

Hello experts,

I am monitoring a specific folder location in a server, if we find files, PowerShell should drop an email to the users with the list of files available on the location. I am using below code and it is somewhat working fine however the format is little weird:

$dirlist = (ls -Path C:\TEMP\temp).Name
if ($dirlist -ne $null)
{
Write-Host “Dear User, nn Script has finished but there are still few files left over as below:”
$From = “xxxxxx@.xx.com”
$To = “xxxxxx@.xx.com”
$dirlist.ToString()
$Subject = ‘Files Found’
$Body = "Dear User, nn Script has finished but there are still few files left over as below: nn "
$body += $dirlist
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}

 

Output is as follow:

Dear User,

Script has finished but there are still few files left over as below:

New Text Document - Copy (2).txt New Text Document - Copy (3).txt New Text Document - Copy (4).txt New Text Document - Copy.txt New Text Document.txt

==============

How do I make sure it lists the file in Tabular format but not on a single line, Would appreciate someone can help in it :slight_smile:

 

 

 

 

Aayoosh

When you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE”, in the “Visual” view you can use the format template “Preformatted”. You can go back edit your post and fix the formatting - you don’t have to create a new one.
Thanks in advance.

This should be enough actually

$dirlist = (Get-ChildItem -Path C:\TEMP\temp | Select-Object -ExpandProperty Name) -join "`n"
if ($null -ne $dirlist) {
    $SendMailMessageParams = @{
        From       = 'xxxxxx@.xx.com'
        to         = 'xxxxxx@.xx.com'
        Subject    = 'Files Found'
        Body       = "Dear User, n Script has finished but there are still few files left over as below: n $dirlist "
        SmtpServer = $SMTPServer
        port       = $SMTPPort
    }
    Send-MailMessage @SendMailMessageParams
}
</pre>

Edit:
The forum software messes up the code. The "n" in the body should be "`n" actually.

Hello Olaf,

Thank you so much for the script. It worked perfectly !

Thank you so much again for your time. Really appreciate it. :slight_smile: