Solved

Powershell Script Error Handling

Posted on 2016-11-16
7
90 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 84

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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
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 84

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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
In this video we show how to create a Distribution Group 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 >>…
In this video we show how to create a Resource Mailbox in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: Navigate to the Recipients >> Resources tab.: "Recipients" is our default selection …

710 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