Answered by:
Execute a code when Send-MailMessage is succesfull if not then do nothing

Question
-
Dear Experts,
I have googled all day to try to solve my problem but so far no luck. I try to create a try/catch/finally code in Powershell. And use the Send_mailMessage command. What I would like is to when a email is send successfully then execute a code to clean up all the files in the c:\temp with extension .xlsx. When the mail fails to send. it has to do nothing. But where can I put the code:
get-childitem "c:\temp" -recurse -force -include *.xlsx | remove-item -force
This is my code:
$username = 'xxxxxxxxxxxxxxxxxxxxxxxx' $password = 'xxxxxxxxxxxxxxxxxxxxxxxx' $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) $attachment = get-childitem C:\temp | where name -like "*.xlsx" $now = get-date try { $Msg = @{ from = 'xxxxxxxxxxxxxxxxxxxxxxxx' to = 'xxxxxxxxxxxxxxxxxxxxxxxx' subject = 'Backup ' + $now.ToLocalTime().ToString("dd-MM-yyyy"); smtpserver = 'xxxxxxxxxxxxxxxxxxxxxxxx' port ='xxx' credential = $creds attachments = $attachment.fullname body = 'Backup ' + $now.ToLocalTime().ToString("dd-MM-yyyy"); } Send-MailMessage @Msg -UseSsl } catch [System.Exception] { Write-host $_.Exception.Message } Finally { Remove-Variable -name username Remove-Variable -name password Remove-Variable -name secpasswd Remove-Variable -name creds Remove-Variable -name attachment Remove-Variable -name Msg }
gr. pTuesday, February 26, 2019 10:18 AM
Answers
-
Send-MailMessage @Msg -UseSsl -ErrorAction Stop
You must tell the CmdLet to throw a catchable error.
\_(ツ)_/
- Marked as answer by PeetK Tuesday, February 26, 2019 11:19 AM
Tuesday, February 26, 2019 10:51 AM
All replies
-
Send-MailMessage @Msg -UseSsl -ErrorAction Stop
You must tell the CmdLet to throw a catchable error.
\_(ツ)_/
- Marked as answer by PeetK Tuesday, February 26, 2019 11:19 AM
Tuesday, February 26, 2019 10:51 AM -
Sorry I don't understand your response.
I have tried the finally-section. But even if the sending of the mail failes it still executes the code in the finally-section.
- Edited by PeetK Tuesday, February 26, 2019 10:56 AM
Tuesday, February 26, 2019 10:55 AM -
What don't you understand. Just use the code I posted.
To understand how to use try/catch see the following:
https://learn-powershell.net/2015/04/04/a-look-at-trycatch-in-powershell/
\_(ツ)_/
Tuesday, February 26, 2019 11:01 AM