简体   繁体   中英

Powershell using send-mailmessage

i have the below code:

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

$message = @{
    to="sender@mail.com"
    from="monitoring@mail.com"
    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!

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="sender@mail.com"
    from="monitoring@mail.com"
    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="sender@mail.com"
    from="monitoring@mail.com"
    subject="testing monitoring"
    smtpserver="mail.com"
    bodyashtml=$false
    body=$files
}
Send-MailMessage @message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM