Continue execution on Exception
Asked Answered
V

4

7

Below is the script I want to execute. The issue here is once an exception occurs it stops executing, I used continue in the catch block but that did not work. How do I get it working even after an exception occurs it should loop in foreach.

I also used a while($true) loop but that went into infinite loop. How to go about it?

$ErrorActionPreference = "Stop";
try 
{
# Loop through each of the users in the site
foreach($user in $users)
{
    # Create an array that will be used to split the user name from the domain/membership provider
    $a=@()


    $displayname = $user.DisplayName
    $userlogin = $user.UserLogin


    # Separate the user name from the domain/membership provider
    if($userlogin.Contains('\'))
    {
        $a = $userlogin.split("\")
        $username = $a[1]
    }
    elseif($userlogin.Contains(':'))
    {
        $a = $userlogin.split(":")
        $username = $a[1]
    }

    # Create the new username based on the given input
    $newalias = $newprovider + "\" + $username

    if (-not $convert)
    {
        $answer = Read-Host "Your first user will be changed from $userlogin to $newalias. Would you like to continue processing all users? [Y]es, [N]o"

        switch ($answer)
        {
            "Y" {$convert = $true}
            "y" {$convert = $true}
            default {exit}
        }
    }   

    if(($userlogin -like "$oldprovider*") -and $convert)
    {  

        LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + "    ")
        move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
        LogWrite ("Done")
    }   
} 
}
catch  {
    LogWrite ("Caught the exception")
    LogWrite ($Error[0].Exception)
} 
Vociferant answered 26/4, 2013 at 5:51 Comment(2)
Why not change $ErrorActionPreference = "Continue" ? Doesn't work for you?Wunder
Is there a specific line that's causing the exception?Optimum
P
12

You use try {...} catch {...} when you want to handle errors. If you want to ignore them, you should set $ErrorActionPreference = "Continue" (or "SilentlyContinue") as @C.B. suggested, or use -ErrorAction "SilentlyContinue" for the particular operation raising the error. If you want to handle errors from a certain instruction, you'd put that instruction in the try {...} catch {...} block, not the entire loop, e.g.:

foreach($user in $users) {
  ...
  try {
    if(($userlogin -like "$oldprovider*") -and $convert) {  
      LogWrite ("Migrating User old : " + $user + " New user : " + $newalias + "    ")
      move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false
      LogWrite ("Done")
    }   
  } catch {
    LogWrite ("Caught the exception")
    LogWrite ($Error[0].Exception)
  }
} 
Penetration answered 26/4, 2013 at 7:51 Comment(3)
Since i wanted to log non terminating errors, setting '$ErrorActionPreference' did not help me much. Only time it worked is '$ErrorActionPreference = "Stop"' but than the execution halts on catch. I wanted to continue exection even on error. Please see my answer, that solved my issue. Thanks for your answer. :)Vociferant
You need Stop as the error action for try..catch to work, because it only catches terminating errors. Without a terminating error there'd be nothing to catch in the first place.Penetration
-ErrorAction doesn't work for exceptions. E.g. if you want to ignore failure of Set-ExecutionPolicy, the only way to get no error output is to Catch[System...] { }. Note you need the space, otherwise Catch is parsed to nothing and that causes an error!Karakorum
A
2

You seem to have placed the "catch" outside the loop body, so that aborts the loop. Put the catch inside the loop

Avernus answered 16/8, 2019 at 20:37 Comment(2)
Please some more explanation and code, as these might help for future referencePeon
In the OP code, the catch block sits outside the loop. Here is an example: foreach($a in $list) { try { dosomething } Write-Output "Yay, I did something!" } Catch { Write-output "Uh-oh. Armageddon." } When the exception is caught, it is caught outside the loop.Avernus
V
0

Modified the code as below. Used the following piece of code after move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false

if($?)
{
  LogWrite ("Done!")
  LogWrite ("  ")
}
else
{
  LogWrite ($Error[0].ToString())
  LogWrite ("  ")
}
Vociferant answered 26/4, 2013 at 7:55 Comment(2)
Don't use $?. Ever. Instead check $LastExitCode (see here).Penetration
Isn't $LastExitCode for executables, not for PowerShell cmdlets, scripts, or functions?Dail
T
0

Something that worked for me is to set the $ErrorActionPreference variable to stop, and then reset it back to continue in the catch block:

$e = $ErrorActionPreference
$ErrorActionPreference="stop"

try
{
     #Do Something that throws the exception
}
catch
{
    $ErrorActionPreference=$e

}

$ErrorActionPreference=$e;
Tuttifrutti answered 24/11, 2014 at 20:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.