Continue Exception

Below is the script I want to execute. The problem here is that as soon as an exception occurs, it stops executing, I used continue in the catch block, but that didn't work. How to make it work even after an exception occurs, it should loop in foreach .

I also used a while($true) , but it went into an infinite loop. How to do 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) } 
+5
source share
4 answers

You use try {...} catch {...} when you want to handle errors. If you want to ignore them, you must set $ErrorActionPreference = "Continue" (or "SilentlyContinue" ) as @CB or use -ErrorAction "SilentlyContinue" for the specific operation that causes the error. If you want to handle errors from a specific command, you should put this command in a try {...} catch {...} , and not the entire loop, for example:

 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) } } 
+7
source

The code is changed as shown below. Used the following code snippet after move-spuser -identity $user -newalias $newalias -ignoresid -Confirm:$false

 if($?) { LogWrite ("Done!") LogWrite (" ") } else { LogWrite ($Error[0].ToString()) LogWrite (" ") } 
0
source

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

 $e = $ErrorActionPreference $ErrorActionPreference="stop" try { #Do Something that throws the exception } catch { $ErrorActionPreference=$e } $ErrorActionPreference=$e; 
0
source

You seem to have put a β€œlatch” outside the loop body to break the loop. Put the catch inside the loops

0
source

All Articles