Email with multiple attachments

和自甴很熟 提交于 2019-12-09 04:48:31

问题


I am working on a PowerShell script for the help desk to use when migrating userhome folders from a server to a NAS device. The help desk user enters the usernames into the "userhomelist.txt" file.

My problem is that I'm not able to get the script to attach all of the log files. Only the last log file is attached to the email. I am thinking I need to use a string for multiple attachments, but I keep thinking there is another way.

#----- STEP #1 retrieve contents of input file ---#
$INPUTFILEPATH = 'c:\temp\userhomelist.txt'

#----- read input file contents ----#
$inputdata = Get-Content $INPUTFILEPATH

#----- Top section of email body ----#
$msgreport = new-object Net.Mail.MailMessage 
$msgreport = "To view log files, go to directory where this PowerShell Script was run from. `r"
$msgreport = $msgreport + "`r`n"

#read in each username
foreach ($username in $inputdata)
{

#----- STEP #2 robocopy files from \\server to \\nasdevice location ----#
Start-Process -FilePath robocopy -ArgumentList "\\server\userhomes\$username \\nasdevice\userhomes\$username /mir /sec /r:1 /w:1 /tee /NP /Z /log+:userhome-move-$username.log"
$file = "c:\temp\userhome\userhome-move-$username.log"
$msgreport = $msgreport + "$username robocopy has been completed." + "`n"

##----- STEP #3 change file and directory ownership to user ----#
Start-Process -FilePath subinacl -ArgumentList "/subdirectories \\nasdevice\userhomes\$username\*.* /setowner=$username"
$msgreport = $msgreport + "$username file and directory ownership changes have been completed." + "`n"
$msgreport = $msgreport + "`r`n"
}

#----- Email Results ----#
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage 
$SmtpServer = "emailserver.business.com"
$SmtpClient.host = $SmtpServer 
$MailMessage.From = "userhome-migration@business.com"
$MailMessage.To.add("helpdeskn@business.com")
$MailMessage.Subject = "User migrations"
$MailMessage.IsBodyHtml = 0
$MailMessage.Body = $msgreport
$MailMessage.Attachments.Add($file)
$SmtpClient.Send($MailMessage)

回答1:


I suggest to use send-mailmessage cmdlet if you are in powershell v2 or v3. It has an -attachments parameter that accept array of string ( string[] ).

You can change your variable $file declaring it as $file = @() before the foreach user loop. Inside the foreach do:

$file += "c:\temp\userhome\userhome-move-$username.log"

change $msgreport as [string] type

and then using the send-mailmessage cmdlet do:

send-mailmessage -SmtpServer "emailserver.business.com"  `
-From "userhome-migration@business.com" -to "helpdeskn@business.com" `
-Subject "User migrations" -BodyAsHtml -Body $msgreport -Attachments $file


来源:https://stackoverflow.com/questions/13167580/email-with-multiple-attachments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!