Email with multiple attachments

I am working on a PowerShell script for a help desk that will be used when moving userhome folders from the server to the NAS device. The help desk user enters the usernames in the userhomelist.txt file.

My problem is that I cannot attach the script to all the log files. Only the latest log file is attached to this email. I think I need to use the string for several attachments, but I keep thinking that 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) 
+6
source share
1 answer

I suggest using the send-mailmessage cmdlet if you are in powershell v2 or v3. It has the -attachments parameter, which takes an array of strings ( string[] ).

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

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

change $msgreport as [string] type

and then using the send-mailmessage do cmdlet:

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

All Articles