2
votes

I am looking to improve an old batch script and upgrade it to powershell, this is a robocopy batch script and i would like it to send a mail with the logfile attatched when it is finished. i managed to get the drive mappings and robocopy part sorted but im having some issues getting the send-mailmessage part to work

`$SourceFolder = "V:\"
$DestinationFolder = "Y:\"
$Dateandtime = Get-Date -format filedate
$password = XXXXXXXXX
$Subject = "Robocopy Results: Backup USA - NL"
$SMTPServer = "mailserver.domain.com"
$Sender = "[email protected]"
$Username = "backupusr"
$Recipients = "[email protected]"
$Admin = "[email protected]"
$SendEmail = $True
$IncludeAdmin = $True
$AsAttachment = $False
$Cred =  new-object Management.Automation.PSCredential $Username, ($password 
| ConvertTo-SecureString -AsPlainText -Force)`

This is the line that causes the script to timeout

Send-MailMessage -SmtpServer $SMTPServer -From $Sender -To $Recipients -Subject $Subject -Body "Robocopy results are attached." -DeliveryNotificationOption onFailure -UseSsl -Credential $Cred

this is the error i recieve

Send-MailMessage : The operation has timed out. At C:\Scripts\bpcti-robocopy.ps1:113 char:1 + Send-MailMessage -SmtpServer $SMTPServer -From $Sender -To $Recipient ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

Any help would be greatly appreciated.

1
quick edit: i managed to get the command to work without a password (i have to manualy enter it) Send-MailMessage -SmtpServer mailserver.domain.com - From [email protected] -To [email protected] - Subject testing -Body "Robocopy results are attached." - DeliveryNotificationOption onFailure -Credential "[email protected]" my question now is what syntax do i use for adding a passwordJuggernaught

1 Answers

1
votes

The -Credential parameter takes a PSCredential object. You can use Get-Credential to interactively create one using a username and password combination. More detail here.

Alternatively, as your password is already in plaintext in your script, you can use the process as described here and construct a new PSCredential.

# Convert the plaintext password into a secure string.
$SecurePassword = ConvertTo-SecureString "XXXXXXXXX" -AsPlainText -Force
# Create a new PSCredential using the username and secure string password.
$Cred = New-Object System.Management.Automation.PSCredential ("[email protected]", $SecurePassword)

Send-MailMessage -SmtpServer mailserver.domain.com -From [email protected] -To [email protected] -Subject testing -Body "Robocopy results are attached." -DeliveryNotificationOption onFailure -Credential $Cred

Beware that the username should include the @domain.com.