Solved

Powershell Script Error Handling

Posted on 2016-11-16
7
34 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Find out how to use Active Directory data for email signature management in Microsoft Exchange and Office 365.
This process describes the steps required to Import and Export data from and to .pst files using Exchange 2010. We can use these steps to export data from a user to a .pst file, import data back to the same or a different user, or even import data t…
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 …
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…

757 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

19 Experts available now in Live!

Get 1:1 Help Now