Solved

Powershell Script Error Handling

Posted on 2016-11-16
7
67 Views
Last Modified: 2016-11-23
I am trying to setup error handling in my powershell script and am unsure how to do it.

My powershell script disables one Transport Rule in Exchange and Enables a different Transport Rule. Once Rule has been enabled an email is sent to me (For privacy reasons I have changed email address and hostname)

I know I have to setup some kind of Try and Catch Variables so I can add Error Handling to Powershell script but unsure where to start.

Any help would be much appreciated. I have attached a copy of the powershell script in a txt file.

Thanks

TroyPowerShellScript.txt
0
Comment
Question by:Troy Graham
  • 3
  • 2
  • 2
7 Comments
 
LVL 2

Expert Comment

by:Chamara Weliwattage
ID: 41890706
you have to do try and catch. Below is very basic example

Try{ <Command> -erroraction Stop
}

Catch{

Write-host $error.message
}
0
 
LVL 83

Expert Comment

by:oBdA
ID: 41891044
Like that, for example:
Try {
	<# Start a Powershell Session and Enable Transport Rule in Exchange 2010 #>
	$PSSession = New-PSSession -ConfigurationName microsoft.exchange -ConnectionUri http://exchsrv.exchange.com.au/PowerShell/ -Authentication Kerberos -ErrorAction Stop
	$WarningPreference = "SilentlyContinue"
	Import-PSSession $PSSession -ErrorAction Stop 2>&1 | Out-Null
	Enable-TransportRule "Australia Hours" -Confirm:$false -ErrorAction Stop
	Disable-TransportRule "NZ Hours" -Confirm:$false -ErrorAction Stop
	$EmailSubject = "You have just run the Transport rule to Enable Aus and Disable NZ"
	$Result = "Everything went fine."
} Catch {
	$EmailSubject = "There was an error trying to run the Transport rule to Enable Aus and Disable NZ"
	$Result = $_.Exception.Message
} Finally {
	<# Close Powershell Session #>
	Remove-PSSession $PSSession
}
<# Send email notification #>
$User = "anonymous"
$PWord = ConvertTo-SecureString –String "anonymous" –AsPlainText -Force
$Creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pword
Send-MailMessage -From "dummy@dummy.com.au" -To "dummy2@dummy.com.au" -Cc "dummy3@dummy.com.au" -Bcc "dummy4@dummy.com.au" `
	-SmtpServer "exchsrv.exchange.com.au" `
	-Subject $EmailSubject `
	-BodyAsHtml `
	-Credential $creds `
	-Body @"
Hi CSG,
<br>
<br>
You have just run the Transport rule to Enable Aus and Disable NZ.
<br>
Result: $($Result)
<br>
<br>
Kind Regards
<br>
Troy Graham
<br>
IT Support Administrator
<br>
joebloe@dummy.com.au
"@

Open in new window

0
 

Author Comment

by:Troy Graham
ID: 41898260
Hi oBda,

That seems to work ok now but how can i get it to check if the Transport Rule is already enabled or not, and if it is throw off error.

e.g. If "Australia Hours" is already enabled, throw off error that says "Australia Hours is already enabled" and end script execution

Cheers
Troy
0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 2

Expert Comment

by:Chamara Weliwattage
ID: 41898470
Hi Troy,

This is a checking condition, not error handling so you have to do a "IF" before try loop. If "IF" condition is true, set your script to go through "try/catch/finally"
0
 
LVL 83

Accepted Solution

by:
oBdA earned 500 total points
ID: 41898599
You query the transport rule and act accordingly.
Try {
	<# Start a Powershell Session and Enable Transport Rule in Exchange 2010 #>
	$PSSession = New-PSSession -ConfigurationName microsoft.exchange -ConnectionUri http://exchsrv.exchange.com.au/PowerShell/ -Authentication Kerberos -ErrorAction Stop
	$WarningPreference = "SilentlyContinue"
	Import-PSSession $PSSession -ErrorAction Stop 2>&1 | Out-Null
	If (Get-TransportRule "Australia Hours" -State Enabled -ErrorAction SilentlyContinue) {
		Throw "Transport Rule 'Australia Hours' is already enabled."
	}
	Enable-TransportRule "Australia Hours" -Confirm:$false -ErrorAction Stop
	Disable-TransportRule "NZ Hours" -Confirm:$false -ErrorAction Stop
	$EmailSubject = "You have just run the Transport rule to Enable Aus and Disable NZ"
	$Result = "Everything went fine."
} Catch {
	$EmailSubject = "There was an error trying to run the Transport rule to Enable Aus and Disable NZ"
	$Result = $_.Exception.Message
} Finally {
	<# Close Powershell Session #>
	Remove-PSSession $PSSession
}
<# Send email notification #>
$User = "anonymous"
$PWord = ConvertTo-SecureString –String "anonymous" –AsPlainText -Force
$Creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pword
Send-MailMessage -From "dummy@dummy.com.au" -To "dummy2@dummy.com.au" -Cc "dummy3@dummy.com.au" -Bcc "dummy4@dummy.com.au" `
	-SmtpServer "exchsrv.exchange.com.au" `
	-Subject $EmailSubject `
	-BodyAsHtml `
	-Credential $creds `
	-Body @"
Hi CSG,
<br>
<br>
You have just run the Transport rule to Enable Aus and Disable NZ.
<br>
Result: $($Result)
<br>
<br>
Kind Regards
<br>
Troy Graham
<br>
IT Support Administrator
<br>
joebloe@dummy.com.au
"@ 

Open in new window

0
 

Author Comment

by:Troy Graham
ID: 41898708
Thanks a lot oBda. Your solution worked like a charm. :-)

Here is what I ended up with. I added a separate email for failure and a separate email for success.

Try {
	<# Start a Powershell Session and Enable Transport Rule in Exchange 2010 #>
	$PSSession = New-PSSession -ConfigurationName microsoft.exchange -ConnectionUri http://exchsrv.exchange.com.au/PowerShell/ -Authentication Kerberos -ErrorAction Stop
	$WarningPreference = "SilentlyContinue"
	Import-PSSession $PSSession -ErrorAction Stop 2>&1 | Out-Null
    If (Get-TransportRule "Testing" -State Enabled -ErrorAction SilentlyContinue) {
		Throw "Transport Rule Has already been enabled"
	}
	Enable-TransportRule "Testing" -Confirm:$false -ErrorAction Stop
	Disable-TransportRule "Testing 2" -Confirm:$false -ErrorAction Stop
	$EmailSubject = "SUCCESS: Transport rule to Enable Aus and Disable NZ"
	$Result = "Everything went fine."

<# Send email notification #>
$User = "anonymous"
$PWord = ConvertTo-SecureString –String "anonymous" –AsPlainText -Force
$Creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pword
Send-MailMessage -From "dummy@dummy.com.au" -To "dummy2@dummy.com.au" -Cc "dummy3@dummy.com.au" -Bcc "dummy4@dummy.com.au" `
	-SmtpServer "exchsrv.exchange.com.au" `
	-Subject $EmailSubject `
	-BodyAsHtml `
	-Credential $creds `
	-Body @"

<font face="Arial" color="#000000" size="2">Hi CSG,</font>
<br>
<br>
<font face="Arial" color="#000000" size="2">SUCCESS: Transport rule to Enable Aus and Disable NZ ran successfully</font>
<br>
<br>
</br>
<font face="Arial" color="#000000" size="2">Regards</font>
</br></br>
<font face="Arial" color="#000000" size="2" style="font-weight:bold">Troy Graham</font>
</br>
<font face="Arial" color="#000000" size="2">IT Support Administrator</font>
</br>
“@


} Catch {
	$EmailSubject = "FAILURE: Error running Transport rule to Enable Aus and Disable NZ"
	$Result = $_.Exception.Message

<# Send email notification #>
$User = "anonymous"
$PWord = ConvertTo-SecureString –String "anonymous" –AsPlainText -Force
$Creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pword
Send-MailMessage -From "notifications@eclgroup.com.au" -To "troy.graham@eclgroup.com.au" -Cc "troy.graham@eclgroup.com.au" -Bcc "troy.graham@eclgroup.com.au" `
	-SmtpServer "fq-exchsrv.eclfuelquip.com.au" `
	-Subject $EmailSubject `
	-BodyAsHtml `
	-Credential $creds `
	-Body @"

<font face="Arial" color="#000000" size="2">Hi CSG,</font>
<br>
<br>
<font face="Arial" color="#000000" size="2">FAILURE: Transport Rule to Enable Aus and Disable NZ didnt run</font>
<br>
<br>
</br>
<font face="Arial" color="#000000" size="2">Regards</font>
</br></br>
<font face="Arial" color="#000000" size="2" style="font-weight:bold">Troy Graham</font>
</br>
<font face="Arial" color="#000000" size="2">IT Support Administrator</font>
“@

} Finally {
	<# Close Powershell Session #>
	Remove-PSSession $PSSession
}

Open in new window

0
 

Author Closing Comment

by:Troy Graham
ID: 41898709
Thanks Again oBda. Your Solution worked like a charm. :-)
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will help you understand what HashTables are and how to use them in PowerShell.
A brief introduction to what I consider to be the best editor for PowerShell.
In this video we show how to create a Shared Mailbox in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >> Sha…
This video demonstrates how to sync Microsoft Exchange Public Folders with smartphones using CodeTwo Exchange Sync and Exchange ActiveSync. To learn more about CodeTwo Exchange Sync and download the free trial, go to: http://www.codetwo.com/excha…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question