Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Powershell Exeception Question

Posted on 2012-03-20
7
Medium Priority
?
384 Views
Last Modified: 2012-03-22
Hi,

I am trying to understand why a simple try / catch block is not capturing exceptions.

From the code below I expect it the output to be:

Start..
Test1..
Exception 1...
Test2..
Exception 2...

However instead I get:

PS C:\> .\exception_test.ps1
Attempted to divide by zero.
At C:\exception_test.ps1:6 char:10
+     $a = 1 / <<<<  0
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

PS C:\>

So what am I doing wrong ?

The code is below.

Thanks,

Ward.

PS testPC is a non-existant pc.

write-Host "Start.."

try 
{ 
	Write-Host "Test1.."
	$a = 1 / 0 
}

catch 
{	
	write-host "Exception 1..." 
}

try 
{ 	
	Write-Host "Test2.."
	$wmi_objects = Get-WmiObject "Win32_Process" -computer "testPC" 
}

catch 
{	
	write-host "Exception 2..." 
}

Open in new window

0
Comment
Question by:whorsfall
[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
  • 3
7 Comments
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745465
You can't divide by 0.  

$a = 1 / 0

What exactly are you trying to do?
0
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745471
Are those supposed to be placeholders for computers you're trying to ping?  If that's the case, it would look something like this:

$Count = $Computers.count

$a = "1/$count"

Does that make sense?
0
 
LVL 8

Expert Comment

by:Brent Challis
ID: 37745535
Your problem with the sample code seems to be that the PowerShell environment is detecting that you have written a divide by zero.  If he code s modified so that it has to run before the problem is detected to try/catch works as you would expect.  e.g.
 Set-StrictMode -Version "Latest"
write-Host "Start.."
$den = 0
try
{
      Write-Host "Test1.."
      $a = 1 / $den
}
catch
{      
      write-host "Exception 1..."
}

try
{       
      Write-Host "Test2.."
      $wmi_objects = Get-WmiObject "Win32_Process" -computer "testPC"
}
catch
{      
      write-host "Exception 2..."
}

produces

Start..
Test1..
Exception 1...
Test2..
Exception 2...
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 1

Author Comment

by:whorsfall
ID: 37745606
Hi,

Hmm. Can u elaborate a bit futther - provide a more detailed explination.

I looked at the Set-StrictMode and still am confused why my orignal code would of not worked.

I am missing the point here :)

Thanks,

Ward
0
 
LVL 16

Expert Comment

by:Dale Harris
ID: 37745650
I think the core of the issue is that you are trying to do an illegal operation to make an error.  The problem is, the try/catch/finally is geared towards legitimate returns of errors.  For example, if you try to ping a null value, I don't think the try/catch would work, but if you try to ping and get an error that the computer could not be reached, it would be thrown to the catch portion.

Does that make sense?
0
 
LVL 8

Accepted Solution

by:
Brent Challis earned 2000 total points
ID: 37745662
The Set-StrictMode is simply my standard starting point and is not actually relevant here.  

What seems to be happening is that when you ask PowerShell to run the script it parses it.  In that process is sees that there is a divide by zero issue as you have hard coded the 0 as the denominator, so it errors out.  This can be seen by the fact that the error message turns up before any of the Write-Host cmdlet output that should have occurred before it gets to the error line.  By changing the denominator to a variable the parsing can't determine that there is an error so the code is executed. We get the Write-Host output, then we get a run time error as the division is performed using a variable that has the value of 0 which is processed in the catch block and then we continue through the code..
0
 
LVL 8

Expert Comment

by:Brent Challis
ID: 37745666
You may also need to set the ErrorActionPreference to enable PowerShell to move past the error as well so that the catch block can process the exception:
$ErrorActionPreference = "Stop"
0

Featured Post

Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

Question has a verified solution.

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

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
In this post we will be converting StringData saved within a text file into a hash table. This can be further used in a PowerShell script for replacing settings that are dynamic in nature from environment to environment.
The viewer will learn how to dynamically set the form action using jQuery.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses

636 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