Having problems grasping error handling.

Hello,

I am new to powershell, scripting, coding etc. Went through the gambit of jumpstart video’s and have been reading through online articles/examples and have been making steady progress but I am now stumped at the behavior I am seeing.

Here is what I am doing (this is not going to be the full code… just the process)

$ErrorActionPreference= “Stop”
Foreach ($c in $computer) { Try{} catch{} finally{} }

In try{} I am using test-connection -computername $c.
In catch{} Right now I am just doing a write-output $Error[0].Exception.Message (to get the value).
in finally{} I am running the rest of my code (Which checks for a registry attribute, creates it if it doesnt exist, or sets the value if it does already exist)

What I am seeing when I specify one computer:
[ul] If try{} does not error it skips catch and finally runs.
If try{} errors (due to inability to resolve/connect) it goes to catch and finally does not run.[/ul]

What I am seeing when I specify two or more computers (-ComputerName Works, Fails)
[ul] If try{} does not error it skips catch and finally runs.
If try{} errors (due to inability to resolve/connect) it goes to catch and finally does not run for either Works or Fails.[/ul]

Why does it stop the whole entire script even through I thought it would be iterating through the script (Foreach) computer specified?

$ErrorActionPreference= “Stop”

does exactly what it says - it stops execution. Any time a try block fails you will hit the catch block. Your catch block list out the error. There’s nothing else to do so execution stops.

What I would do is reorganise your code

$oldvalue = $ErrorActionPreference
$ErrorActionPreference= "Stop"
Foreach ($c in $computer) {

 Try{
 if (Test-Connection -Count 1 -Quiet -ComputerName $c){
   do stuff

 }
 else {
  Write-Warning "Can't connect to $c"

 }
 
 
 
 } 
 catch{
  
  whatever you need to catch errors on the reg key setting

 } 
 
 
 }


$ErrorActionPreference=$oldvalue

The important part of your processing is the registry key actions not testing the connection

Thanks,

I have the registry actions working. And I could have even cheesed it by increasing my else chain but then it would “try to connect” 4 times and then print out an invalid message for a non-existent server. My goal was to force “Fail” computer to not attempt to modify registry values while the good ones work.

I see how you changed the precedence of code execution. That makes sense and I suspect it will fix my problem. So thanks a bunch.