Dridhas
Dridhas

Reputation: 45

Powershell using send-mailmessage

i have the below code:

    $file = Get-ChildItem -Path C:\MonitorTest | where {$_.LastWriteTime -lt (Get-Date).AddHours(-4) }

$message = @{
    to="[email protected]"
    from="[email protected]"
    subject="testing monitoring"
    smtpserver="mail.com"
    bodyashtml=$true
    body="$file.Name"
}

Send-MailMessage @message

the thing i have is that on Body, using "" it prints the content of the variable $file.name in one single line. (New Text Document (2) - Copy.txt New Text Document (2).txt New Text Document (3) - Copy.txt)

if i only select $file.name and run it, it will print it in lines New Text Document (2) - Copy.txt New Text Document (2).txt New Text Document (3) - Copy.txt

if i run the send-mailmessage @message, the email comes thru, but its on one line as if running only "$file.name"

these are the contents of $file:

    Directory: C:\MonitorTest


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         8/13/2020   3:57 PM              0 New Text Document (2) - Copy.txt
-a----         8/13/2020   3:57 PM              0 New Text Document (2).txt
-a----         8/13/2020   3:57 PM              0 New Text Document (3) - Copy.txt
-a----         8/13/2020   3:57 PM              0 New Text Document (4) - Copy.txt
-a----         8/13/2020   3:57 PM              0 New Text Document (5) - Copy.txt
-a----         8/13/2020   2:13 PM              0 New Text Document.txt

Can anyone help me figure this out please? im running bonkers trying to figure this out.

Thanks in advance!

Upvotes: 0

Views: 329

Answers (1)

David Martin
David Martin

Reputation: 12248

You are sending as html, so you will need html line breaks <br>, which can be achieved as follows:

$filesHtml = (Get-ChildItem -Path C:\MonitorTest | where {$_.LastWriteTime -lt (Get-Date).AddHours(-4) } | Select-Object -ExpandProperty Name) -join "<br>" | Out-String
$message = @{
    to="[email protected]"
    from="[email protected]"
    subject="testing monitoring"
    smtpserver="mail.com"
    bodyashtml=$true
    body=$filesHtml
}
Send-MailMessage @message

Or you can send as text:

$files = Get-ChildItem -Path C:\MonitorTest | Where-Object {$_.LastWriteTime -lt (Get-Date).AddHours(-4) } | Select-Object -ExpandProperty Name | Out-String
$message = @{
    to="[email protected]"
    from="[email protected]"
    subject="testing monitoring"
    smtpserver="mail.com"
    bodyashtml=$false
    body=$files
}
Send-MailMessage @message

Upvotes: 1

Related Questions