Solved

Powershell Script Error Handling

Posted on 2016-11-16
7
56 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

This article explains in simple steps how to renew expiring Exchange Server Internal Transport Certificate.
This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
In this video we show how to create an email address policy 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 Mail Flow…
In this Micro Video tutorial you will learn the basics about Database Availability Groups and How to configure one using a live Exchange Server Environment. The video tutorial explains the basics of the Exchange server Database Availability grou…

929 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now