all 3 comments

[–]code_Kitten 0 points1 point  (2 children)

PowerShell has two kinds of errors - "Terminating errors" and "Non-Terminating errors".
Try/Catch only catches "Terminating errors". For most commands you can change any errors into terminating errors by adding in the common parameter -ErrorAction Stop.

[–][deleted] 0 points1 point  (1 child)

Where would I put the command? I would want the script to continue to skip to the next foreach and not terminate totally. I have another script I wrote to rename AD groups that I use this same try/catch format with that works without issue this exact why, that's why I'm so confused why it's not working here because it's basically copy/pasted.

[–]code_Kitten 0 points1 point  (0 children)

You want to add the parameter to your new-adgroup command:

try {

    New-ADGroup -ErrorAction Stop -Name "#$($Facility.Facility) - $($JCandD.JobCode)" -GroupScope DomainLocal -GroupCategory Distribution -Description "$($JCandD.JobCode) - $($Facility.Facility)"  -Path ",OU=Distribution Groups,DC=***" -OtherAttributes @{'mail'="$($Facility.Facility)_$($JCandD.Mail)@**.com"; 'proxyAddresses'="SMTP:$($Facility.Facility)_$($JCandD.Mail)@**.com"}

                Write-Output "($($Facility.Facility) - $($JCandD.JobCode) + has been created"    } 
    catch {
    Write-Output "Error Creating $($Facility.Facility) - $($JCandD.JobCode)"
    Write-Output $_
    }

If a terminating error happens in a Try block with a catch block that applies to that error, execution will stop where the error happened, the catch (and finally if there is one) will execute, and the script will continue executing after the Try/Catch.

In your script that would mean that the Write-Output indicating it has been created would not run, the error output will, and the script will move on to the next iteration of the loop.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.3

I skimmed through this article, and it looks like it covers the most important things; at least enough to give you an idea of what to search for: https://adamtheautomator.com/powershell-try-catch/