Powershell - Continuing script once an error has occurred

1.3k Views Asked by At

In the script below I get it run fine, however once an error occurrs it fails to continue where it left off before the error, I am a little confused as to what I am missing on this, so any help would be great.

First off, it loads a text file that contains a list of distribution groups, this then queries this list with exchange to get the exact match displayname and then cycles through a CSV adding each user to the distribution list, this all works fine, it's when an error occurrs that is the issue.

the catch statement understands the error and then carries out the tasks, once the task is complete it runs the script from the forloop in the catch statement and not in the try.

I have added the function UpdateDistros

To allow the script to run again, but the problem is it rus through the entire text file again instead of starting at where the error occurred, even if its at line 1 or line 25.

Below is the code;

##                                                  ##
##  Adds users from text file to distributon lists  ##
##                                                  ##
######################################################
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName 'UserPrincipalName'
Function UpdateDistros{
$ErroractionPreference = 'Stop'
$Path = "C:\INSTALLS\Exchange-Distro_Lists\Data"

$res = $Path+"\Results"
$txt1 = "Distros.txt"
$txt2 = "Results.txt"
$txt3 = "Mail_Contacts.txt"
$txt4 = "Errors.txt"
$DS1 = gc $Path"\"$txt1  # Gets information from a text file
$1 = "Error Occurred"
$R1 = $res+"\"+$txt2
$R2 = $res+"\"+$txt3
$R3 = $res+"\"+$txt4
try{
Foreach($DS in $DS1){ # Cycles through text file
$DSG = Get-DistributionGroup -identity $DS | Select * -ExpandProperty Alias # Gets display name for distribution group
$DS2 = $path+ "\"+ "$DSG.csv"
$NUS = Import-csv $DS2 
#Foreach { $_ + '@zenith.co.uk' } | ` # ammends all users in each text file to contain @zenith.co.uk
#Foreach { $_ –replace “ “,”.” } # ammends all users in each text file to contain @zenith.co.uk
Foreach($NU in $NUS){ # Cycles through each record in each text file
$N1 = $NU.DP
$N2 = $NU.EM
#$NU
Add-DistributionGroupMember -identity $DS -Member $N1 #Adds each record to the correct distribution List
"$N1 added to $DS"  | Out-file  $R1  -Append
Write-host "Completed Script"
}
}
}
Catch{
$Erw = $_.Exception.Message
$Erw = $Erw -replace """",""
$NMC = get-content $DS2
$Rers = "Couldn't find object $N1. Please make sure that it was spelled correctly or specify a different object."
$Erw
$Rers
$A1 = $N1 -replace "\s",""
if($Erw -contains $Rers){
Foreach($NM in $NMC){
    Write-host $1
    Write-host $Erw
    $Unq = 'There are multiple recipients matching identity "$N1". Please specify a unique value.'
    $ERM = $_.Exception.Message
      if($ERM -contains $Unq){
      $NU = $NU + '- Cartwright' 
      New-MailContact -Name $N1 -ExternalEmailAddress $N2 -Alias $A1
      "New Mail contact created for $N1" | Out-file $R2 -Append -ErrorAction continue
      UpdateDistros
      }
      ElseIf($Erw -contains $Rers){
      New-MailContact -Name $N1 -ExternalEmailAddress $N2 -Alias $A1
      "New Mail contact created for $N1" | Out-file $R2 -Append -ErrorAction continue
      UpdateDistros
      }
      Else{
      $Erw | Out-file $R3 -Append -ErrorAction continue
      UpdateDistros
      } 
      }
}
Else{
      $Erw | Out-file $R3 -Append -ErrorAction continue }
      UpdateDistros
}
}
UpdateDistros
1

There are 1 best solutions below

0
On

You should not put the entire body of your script in a try/catch block. Doing this makes it really hard to tell where the error occured and how to deal with it.

First, delete the try/catch blocks you have.

Next, add one specifically for the issue you want to deal with. You said that you the script fails to continue when it can't add a user to a distribution group, making that a good place to add handling.

Also, I'm moving the comment to the top of the line, instead of the end.

Full lines of text are hard to read, but relatively short columns can be scanned easily.

try{
   #Adds each record to the correct distribution List
   Add-DistributionGroupMember -identity $DS -Member $N1 
}
catch{
   $message = "Failed to modify group $($DS) with new member $($N1)"
   Write-warning $message
   $message | Add-content C:\pathTo\SomeLogfile.txt
   CONTINUE
  }

The Continue command in the end is a special PowerShell flow control command.

It means 'Stop processing this item in our current loop and move on to the next one`.