Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue execution on Exception

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)
} 
like image 897
Ishan Avatar asked Apr 26 '13 05:04

Ishan


2 Answers

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)
  }
} 
like image 105
Ansgar Wiechers Avatar answered Nov 04 '22 04:11

Ansgar Wiechers


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

like image 32
Kurt Hill Avatar answered Nov 04 '22 03:11

Kurt Hill