2

I have a few selected items which the user selected in a gui script, those represent GPO now i have the OU he would like to link them to. Code works but i want to result to the user which were link and which couldnt be linked because they are ALREADY linked But this try catch wont do that for some reason, the gui output the succssesful links and write to console errors where the links already exist

$ResultsTextBox.clear()
 #$listBox1.selecteditems
 $SWITCH = Get-ADOrganizationalUnit -filter *  -Property CanonicalName | Where-Object {$_.CanonicalName -eq $listBox2.SelectedItem}

 forEach ($line in $listBox1.selecteditems){
 #Link each selected item GPO to the OU
 try {
    New-GPlink -name $line -target $SWITCH
    $ResultsTextBox.AppendText("`n GPO: $line HAVE BEEN LINKED Successfully.`n")
        }

    catch{$ResultsTextBox.AppendText("`n COULDN NOT LINK GPO: $line TO $SWITCH `n")
    }
 }

Whats wrong here?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Shahar Weiss
  • 141
  • 1
  • 2
  • 11
  • Try/catch is only for script terminating or command terminating errors. I would test $? instead. – js2010 May 15 '20 at 14:16

2 Answers2

6

The Try-Catch block will only catch terminating errors. You can do this by either setting the special ErrorPreference or ErrorAction variables.

Method 1:

This method causes almost every cmdlet to terminate script execution whenever an error occurs. You can simply do this if it satisfies your need:

At the top of your script declare

$ErrorActionPreference = 'Stop'

Method 2:

Using this you can control how different PowerShell cmdlets will behave during an error, and will hence provide you with more control:

# For every cmdlet inside the try block add -ErrorAction to Stop for the try block to "catch".
New-GPlink -name $line -target $SWITCH -ErrorAction STOP

Please check about_try_catch_finally.

Vish
  • 466
  • 2
  • 12
4

Either add -ErrorAction Stop to every command you want to Catch:

Try {
    New-GPlink -name $line -target $SWITCH -ErrorAction Stop
}
Catch {
    $_
}

Or set

$ErrorActionPreference = 'Stop'

at the start of your script.

Scepticalist
  • 3,737
  • 1
  • 13
  • 30