Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Yet another Try Catch question. Iterating through a ForEach loop

$
0
0

Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting  to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.

If I was doing It in VBScript I’d do this:

For Each Thing In colThings
Open Thing
	If Err.Number <> 0 Then“oops”
	Else
	    Do stuff
	    Do stuff
	    Do stuff
	End If
Next

This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?

ForEach ($subKeyName in $subKeyNames)
{
try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
	catch{$return = "error"	}

	If($return -eq "error" )
	{“Oops”
	}
	Else
	{
  	    Do stuff
	    Do stuff
	    Do Stuff
	}
}



Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>