Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I wrote a PowerShell script which is supposed to send emails automatically, but sometimes the email won't send out due to a network issue.

Here is how I'm sending email:

$smtp_notification.Send($mail_notification)

Here are the error logs:

Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:1 char:24
+ $smtp_notification.Send <<<< ($mail_notification)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Is there anyway to re-run the sending line when I met this failure? Can anyone give me some suggestions please?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Put a loop with a try block in it, very simplistically:

$worked = $false
while (-not $worked) {
  try {
    #Perform command to retry, passing -ErrorAction Stop

    $worked = $true  # An exception will skip this
  } catch {
    # Should check to retry: error record is in $_
  }
}
share|improve this answer
    
Thanks very much Richard, this is really usful! –  pansal Apr 8 '12 at 2:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.