Yet another Try Catch question. Iterating through a ForEach loop

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

 
I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

Similar Messages

  • Yet another MBA connection question

    I just purchased my MBA in July and it started off working beautifully. Just in the past month or so my internet connection has gotten a bit lousy. My Airport says I have a full connection to the internet yet pages either never load and sit in internet limbo forever or i get a "safari can't open the page - operation could not be completed' message pop up. I bought this computer for it's portability, but no matter how light and thin a computer is made, when it has no internet it is a useless brick. Is there anything i can do to fix this? I am a new mac user so if you can put it in english that would be great, most of this mac-ese is still a bit greek to me!

    Do you have any other computers on your wireless network? Are they running ok? Do any of them run Torrent software? Or on your MBA?
    Have you taken your MBA to another location with a different wireless router and tried it? was the connection ok from there?
    I would try it from another location first - that will narrow down the issue instantly to either your MBA - or something with your home network.

  • Try - catch question..

    hello..
    i was wondering if i can use a try-block and catch a built in exception without explicitly throwing the exception..
    example:
    try{
    foo[5] = 'A';
    catch (IndexOutOfBoundsException e)
    { blah blah
    is this possible w/o throwing the IndexOut... exception in the try statement?

    You can only catch those exceptions that are (or could be) thrown. The reason your code snippet works is that the exception you're catching is a subclass of RuntimeException. You can always catch any RuntimeException and the compiler will OK it, and you don't have to declare them as being thrown either. If you try to catch an Exception that isn't a RuntimeException (like java.lang.Exception) and isn't thrown, you'll get a compile error. That said, I agree that this isn't the way to do it here.

  • Yet Another Hard Drive Question from a Mac Newbie

    I apologize in advance for the length of this post -- as I state in the subject line, I am a complete Mac newbie.
    I just took delivery yesterday on a new (early 2008) Mac Pro. I purchased and installed an additional 8GB RAM, and ordered it with a 500GB HD (Seagate, it looks like) and purchased two 750GB Hitachi HDs for bays 2 and 3. I will be doing a fair amount of photo editing, and also plan to partition the OS drive to run XP using bootcamp, but also plan to use VM Fusion.
    I am thinking of partitioning the boot drive with 250GB for OS X and apps, 150 GB for XP and apps, and ~66 remaining possibly to be used as scratch memory for CS3, though it sounds like this may not be enough. The bay 2 Hitachi would be used for all my user data (photos, music, docs, etc.) bay 3 would be for backup initially, possibly using Time Machine? (other recommendations welcomed). As space becomes an issue in the future, I will invest in a fourth internal HD, and at least 2TB external HDs for backup.
    Does this seem like a reasonable plan? If so, how do I go about formatting the drives and installing boot camp, Fusion, etc., and in what order? Also, how best do I organize my existing files from my current Windows machine as I copy them to the new user data HD, so they can be accessed as needed by both OS X and XP?
    Thanks for your help.

    I like the boot volume to never get beyond 50% used. Enough room for burning dual-layer DVDs can be 50GB for best results. And to force the system to use the first outer tracks.
    I hope you are concurrently zeroing both drives. SoftRAID is my choice for driver for RAIDs and you can cancel safely at any time. There are also excellent tools for checking sectors and mapping out bad blocks.
    I put Vista on its own 10K Raptor. I had it on the boot drive but I am always changing my mind, my drives and setup. Vista needs at least 40GB and that is with all my major documents and files on another drive which holds 150GB out of 450GB.
    You set the preference for what drive to use as scratch in CS3 or other programs. And you want to disable Spotlight indexing on any scratch or editing partition. Scratch can be a drive, a volume, a stripped array. Any 'normal' partition though don't use the default (journaling) feature is all.
    How large? I'd have to see and know how large files, work flow, and how long you work between projects. The nice thing, erase the scratch volume between projects but it is possible to use 300GB when you work on 1.5GB files and above.
    One early Mac Pro owner wasn't able to work as they wanted until they had 10-12GB RAM, boot RAID0, and RAIDs for scratch and data (saving 2GB files and not having to wait forever, which even a minute can feel like forever).
    Disk Utility: Partition. You can even partition 2+ drives, just make them the same, and first create 2 partitions (100GB on each?) and then stripe the first "Untitled 1" of each into 100GB x n array. Stripe or mirror the "Untitled 2" or leave those are two unique non-RAID volumes. Sounds harder than it is.
    Scratch = temp space and designed to not be saved, to be erased as needed.
    SoftRAID.com 3.6.6 makes it easy to create, delete, erase volumes and arrays as needed. Leopard has improved on non-RAID but not with RAIDs (for those that change their minds).

  • Yet Another Time Sheet Question

    Hello, Everyone:
    I know there have been other posts on this subject, but none of them have met my needs. I recently began my freelance design career and would like to keep track of my hours in spreadsheet form. I know nothing of spreadsheet applications whether it be Excel or Numbers. I need a basic rundown of how to make my spreadsheet do what I want.
    I'd like my sheet to have the following columns:
    *Date | Start Time | End Time | Total Time*
    Now, I have seen where the application renders the time in decimal form, which is fine, but would it be possible to show the time in hours and minutes, like 1 hr 43 mins? I would like to know how to get both sorts of results, if possible. If not, I'll settle for decimals.
    In any case, if someone could show me step-by-step how to meet this task, I would really, really appreciate it.
    Thanks in advance!
    Message was edited by: Ancient Console
    Message was edited by: Ancient Console

    AC,
    Your use of the time calculations is a simple as can be.
    Select column A and format it as Date&Time, and set Time format to None
    Select columns B and C and format as Date&Time, and set Date format to None
    Select column D and format as Duration, adjust the slider to cover only hours and minutes, set the format as you wish, H:MM would work.
    In the first data row of column D, enter the equation: =C-B
    With the first equation in D selected, select the rest of the cells to the bottom and Insert > Fill > Fill Down.
    Enter some data. The result should appear in column D. Now you may not like looking at zeros in the rows where you haven't yet entered times. So, select column D and in the Cells Inspector click the Conditional Format Show Rules button. Choose the rule: Equal To and type a zero into the field on the right. Then click Edit, followed by a click on the rectangle to the right of the word Text. In the colors panel that pops up, cllick the plain white square next to the upper left corner. Now click Done.
    That's all there is to it.
    Jerry

  • Yet another colour management question

    Hi folks,
    I've read several of the very detailed colour management posts/threads here already but haven't found the answer(s) I'm looking for. So I'm hoping that some of the experts might be able to spare me some time and input...
    I am running a Windows 7 (32bit) environment with a Dell u2711 Ultrasharp display attached. I let the monitor warm up for close on 30 minutes and ran an 'Easy' calibration with a Lacie eye-one device using the Gretag Macbeth 3.6 software. (I guess I could have used the 'Advanced' calibration option but thought I'd save myself some time and was always pleased with the results on my older Sony CRTs.)
    I'm running LR3.2 and CS4. Viewing RAW images in LR the skin tones are way too saturated, but when I export the images as sRGB JPEGs the results look very pleasing when viewed in Windows Photo Viewer (far less saturated). If I open the same image in IE, it looks identical to the way it looks in LR. (I don't have Firefox installed so haven't compared that). If I open the image in CS4 by default it looks the same as it does in Windows, but if I change the Proof Setup to Monitor RGB it matches what I am seeing in LR and IE.
    I'm guessing this is somehow related to the new wider gamut range that this monitor can display (compare to my previous CRTs). I read in one of Jao's posts that LR is always right and other non-managed apps will do weird things on high-end displays. IE is not colour managed so why would it display colours very similar to what I'm seeing in LR, when the standard Windows image viewer is displaying colour far less saturated (which seems to be the opposite to what others are experiencing)?
    I generally always export as sRBG jpeg as the images usually go online, but this set is going to a client who will most likely be taking them for printing as well as viewing on a PC.
    Looking forward to your input on this.
    Kind regards,
    Chris

    Hi again all,
    I've finally found some time yesterday to investigate this further and re-calibrate my monitor.
    I nuked the previously created ICC monitor profile (so that there was none applied) and set to work with my Lacie Blue Eye device and the Lacie Blue Eye Pro software package. I set my preferred settings to 6500K, Gamma 2.2, 120cd/m2 and put the monitor into 'Standard' colour preset. I ran a test on those settings and while the colour and gamma levels were close-ish, the Lum was in the mid-high 200s...way too bright. (No wonder I felt like I was getting a tan sitting in front of the monitor. LOL!) DeltaE scores were okay but not great... Time for the manual calibration.
    Set the monitor into 'Custom' colour preset and fired up the Lacie calibration software for the full calibration. Can't remember exactly how far the brightness and contrast controls had to come down, but from memory it was about 30 and 50 respectively. The RGB levels ended up in the high 80s each from memory. Ran the calibration, applied the newly created profile (double checked it was applied in Control Panel | Colour Management). Ran another test report with the Lacie software and got colour, gamma and lum results 0-1% from target, and average dE scores of 0.4, max dE of 0.7.
    RAW files in LR and PS CS4 appear the same, sRGB jpeg exports viewed in Windows Photo Viewer and Firefox appear the same, IE is still a bit out, but that's expected/known.
    I took the (exported jpeg) images to another computer with a cheapy (uncalibrated) LCD monitor and the results were perfectly fine when viewed in Windows Photo Viewer.
    Having greatly reduced the brightness of my monitor I should hopefully reduce the likelihood of having issues with prints coming back too dark. Of course I know I can get hold of the printer profiles from my lab and softproof the images in CS4 when it comes to that anyway.
    Thank you all for your input and feedback on this matter. Everything seems to be resolved now.
    Chris

  • Yet another file sharing question...

    So I've read the posts and several articles and I still can't get this thing to work.
    System setup:
    1) MacLion as the main source with users 'administrator' and 'developer' both admin accounts.
    2) MacLeopard as the client with user 'administrator' an admin account.
    Folder setup on Lion (Get Info):
    1) SharedAdmin > owner admin, group groupAdmin, mode 0755
    2) SharedDevel > owner devel, group groupDevel, mode 0755
    Accounts on Leopard:
    1) Administrator/groupAdmin (same as Lion,
    Objective:
    I'm trying to mount both shared folders on Leopard
    can I use two different login from Leopard
    do permissions effect file sharing

    Right, I think I've got it...
    I'm trying to logon from a Leopard machine to a Lion machine that has got two shared folders created on it using different accounts.
    I can logon to one shared folder with the appropriate account, that preserves the users and permissions, but when I try to logon to the other shared folder Leopard does not present the logon window and used the previous logon details that messes up the users and permissions.
    Am I going about this the right way? And if so wht can't I use two different logon details for the respective accounts?

  • Yet Another Latency Issue Involving Audio through a 1620 into Logic 9

    Hi. Let me apologize in advance for my ignorance, and let me acknowledge that there are lots of tips on latency all over this and other sites.
    I haven't found the answer despite some extensive looking.
    I'm running Logic Studio / Logic 9 on a 32-bit only 2008 iMac.  I am using a Mackie Onyx 1620 [not 1620i] with Firewire InterfaceLogic as my audio interface.
    I am tracking audio into a project with both MIDI tracks and Audio tracks.  I have established an audio loop as an augmented click track.
    I have set latency to a low setting / buffer size in general preferences, and I have engaged "low latency" mode during audio recording.
    I have no problem monitoring through my Mackie Onyx 1620 [not 1620i], with no audible latency or delay problem at all whilst tracking.
    When I then play back the audio tracking, it is about 240 ticks off -- a dramatic latency problem.
    The problem exists even where I have no other tracks beyond my audio loop, and where there are no effects on the audio loop/click track.
    In other DAW setups, I've experienced latency in hearing my backing tracks and having an audible delay from latency in monitoring my input track.  This is effectively the reverse.
    Any ideas?  And again, I am woefully under-educated in the area.  With your kind help, I intend to remedy that . . . .
    Thanks very much.

    Pancenter, thanks for responding and trying to help.
    if so, you have a misunderstanding regarding latency.
    I can promise you that you're right!
    My understanding of latency in a nutshell: it is the small but perceptable delay [from "withholding" of signal] caused as a signal travels from point to point -- both (1) physical point-to-point (for example, from Mac processor to FW jack out on Mac through FW cable to FW jack in on interface, through cable out to monitor speakers or headphones); and
    (2) processing point to point (from recorded audio track through multiple plug-ins on channels strip to bus or master out, through plug-ins on each of those).
    I already know that I likely am wrong about this, or am at least incomplete.
    Based on that understanding, the problem I'm experiencing defies latency as I understand it, and defies logic (no pun intended; I just mean it makes no sense, as I'll explain below).
    What effects do you have on the master bus?
    None.  I had none in the original project I described in my first query, and have none on a simplified experiment project I've conducted since (after reading your response).
    If you are monitoring through the Mackie and NOT using Logic's software monitoring there is no need to set the Preferences/Audio/ I/O Buffer to a low value, set it to 256.  You also don't need to use Low Latency mode if you're monitoring through the Mackie.
    Here, I think I understand, but am not sure. 
    I am definitely monitoring through the Mackie in an absolute sense -- the returning signals from my DAW are coming in to the Mackie and (a) going out the 1620's headphone jack; (b) going out the 1620's master out to a Mackie Big Knob; and (c) going out the Big Knob's headphone jack, or to powered Mackie 824s.
    [No, I'm not a Mackie devotee; I just happened across the gear at great prices, and thought I understood it.]
    I don't think, though, that I'm "monitoring through the Mackie" as you intend it.  For my simple experiment, I established an audio drum track as a click track.  Each of the transients falls right on the metronome click/ beat location, so I know that it's "good."  I then plugged a Precision bass into the Mackie (channel one), with an audio track in Logic with "Input 1" as the input source. There are no plugins on the Precision track's channel strip.
    Because the Mackie FW interface  on the 1620 sends post-gain but pre-fader, I was able to turn down all faders on the Mackie except the master out.  When muting the Precision channel strip in Logic, I hear NO Precision.  *Nothing from the Precision gets to the monitors if the faders are down and Logic is not sending signal.*  If I then "de-mute" the Precision in Logic, I hear signal through the master line in the Mackie 1620. 
    In this setup, I assume I am not "monitoring through the Mackie," but I'm not sure.  I think that I'm "monitoring through Logic," and that's why I've engaged low-latency and set the preferences to minimize latency.
    we need to establish your setup, how you're monitoring, and what effects are on the master bus. (if any)
    In my simple experiment, with Logic set up to minimize latency, and with no plugins on the Logic master, I engaged "record" in Logic (only on the Precision track with no plugins), and I then played simple quarter notes on the Precision in time with the drumbeats in my Logic "clicktrack."  By playing simply like that, I confirmed that I am "in time" as far as my ears can perceive.  I then hit "Stop" in Logic.
    Upon playback, my Precision is perceptably (about 240) ahead of the click track !
    In my understanding of latency, at the worst the Precision should have been late because the Clicktrack would have been traveling through Logic's processing and down the lines to my monitors.
    Again, thanks a ton for trying to help me out here.  I hope that this description makes it easier.

  • Yet another how to * question

    Hi guys,
    Fall semester is ending next week, and I want to find a job by December. Any idea on how to work it out in this shrinking job market?
    Do you think Sun certified java developer certification might be something good to have under the belt? I remember the programmer cert helped me quite a bit in having the last job.
    A little info on me:
    location: Los Angeles
    education: sophomore college student
    java work experience: 1.5 years
    certificaitons:
    Sun certified java programmer
    IBM certified solution developer(Jcertify level II) on WebSphere 3.5
    I really appreciate your spending time on this offtopic post.
    Thanks.

    If you could only choose one, which would be better,
    experience or certification?That's a very difficult question. I think that experience vs. certification is like asking whether apples are better than organges; they're simply different, but typically compliment each other very well.
    While experience demonstrates nothing but the fact that you've been doing something for a long time, most people choose to take advantage of their long stint in the field to refine their skills and become more knowledgeable about it over time. Presumably, if you've kept jobs for long enough, you are able to write a program; hopefully, a half-decent one.
    Certification, on the other hand, displays that you have learned the syntax of a language, the API of a technology, the intended uses, etc., but not that you can actually use it to its full potential. Using a technology is as much about knowing what not to do as it is knowing what to do; experience helps with the former. Certification may be considered sufficient for junior software developers, rather than engineers, who do not necessarily take part in the design of the system that they are developing for, but is simply not enough in most cases.
    As long as one is not stuck in the past and welcomes change, my conclusion would be that one's experience weighs more heavily than holding a certificate. Having said that, if you lack experience, I think that the studying and work required to get a certificate can do nothing but help you out. Again, neither is enough to judge somebody's skills except for at a birds-eye level.
    In response to the original poster, I think that having a genuine passion for programming is one of the greatest job-landing tools you can ever have. Learn as much as you can, utilize your knowledge, love it, and display your skills to your would-be employers; you'll win out in the end.

  • Yet another Optical drive question

    A few months ago I upgraded to a Samsung lightscribe DVD/CD burner, It was working pretty decent (i had osx 10.3.9). Then I upgraded to osx 10.5.8 and I began to notice a slight problem with disk ejecting. At this point this was just a nuisance. Now, I tried loading Final Cut studio 2 and I popped in dvd and everything started ok but when it came time to load the next disk it failed to eject the dvd. I couldn't get it out, I eventually had to manually eject. Upon doing so, I put in the next DVD and nothing happened. The installer was still asking for the next DVD. What gives?

    Hey Daddypaycheck, here is the latest on this issue, once I was able to extract it and restart, the drive seem to work like a champ. I tried loading the software but I ran into the same problem..... I will try the SMU if you think that will help.

  • And yet another reverse telecine question. =)

    Okay so I shot the footage in 24p advanced on a dvx100b. I batch reverse telecined in cinema tools. It worked fine except for the first frame of some of the final reverse telecined files. Only on some of the files (randomly) the first frame is interlaced. This only happened to some of the files and it is not really a big deal because there is nothing important usually in the first frame but it is a little worrying. Could it be because I didnt really pay attention to which of the 5 frame set (0-5/A-D frames where frame 3/C is the interlaced frame in 24p advanced) was captured as the first frame during capturing? I have heard that you must capture the 0/A frame as the first frame for reverse telecining/advanced pulldown removal to work. Is this true. Even if so, the whole clip other than the first frame is still fine so, any ideas?

    Ive received an answer to this in another forum. It is due to the fact that cinema tools has no other field to combine with for the first frame depending on which of the 5 field sequence it started recording in. It is really no problem because it is only the very first frame that is affected.

  • Yet another album artwork question

    Hi there everyone. I'm trying to add a few more songs to my 80GB iPod classic. I've taken the time to go through my 200+ albums and either use the "Add album artwork" option or search through Amazon.com for album photos, in the end, all of my songs has an image associated with it. Today I tried adding some mp3s from an album that was originally made of ogg files. After converting the files and adding the songs to iTunes, I noticed that 2 of the songs didn't have album art. I've tried everything, including the suggestion of *rebuilding the artwork cache* at least 3 times, to no avail. Is there anything else I can do? Or do I just have to wait till the next upgrade to iTunes is released and hope things work themselves out?
    Thank you in advance for your time.

    To clarify, do you mean that in iTunes the artwork is fine, but on the iPod it isn't there?
    Have you tried REMOVING the tracks from the iPod then resyncing them back on?
    Regards,
    Patrick

  • Yet another transfer/sync question...

    I've authorized my new laptop.
    I know how to transfer "purchased" songs to it.
    I CAN NOT access original hard drive which also holds songs burned from CD (but most of my library is on the iPod as well).
    Q: Will connecting iPod to the new laptop, sync its song list (including the non-purchased songs) TO the new lap?
    Thanks
    Drock j

    dockj wrote:
    Q: Will connecting iPod to the new laptop, sync its song list (including the non-purchased songs) TO the new lap?
    NO.
    To copy songs from an iPod to a computer, you need 3rd party software. Search this forum for a very informative post by Zevoneer on the topic.

  • (Yet another) Modal Dialog question...

    I'd like to have a modal dialog that has a short message and 8 buttons. A UIAlertView works fine here except the buttons are huge and look bad.
    The buttons are labeled 1-7 and cancel so I'd like them laid out as follows:
    1 2 3
    4 5 6
    7 Cancel
    I've tried presentModalViewController but that doesn't look as nice as UIAlertView. I looked into extending UIAlertView but couldn't figure out how to change the layout of the buttons.
    Can some one point me in the right direction on how to go about this?
    Thanks

    If your dialog needs 7 buttons then it probably shouldn't be a dialog.

  • Yet another Flash 5 question..

    Does anyone know how to make a simple countdown clock (Days, Hours, Minutes Seconds) that I could set a date in Actionscript it would countdown to?
    Thanks. (I don't even know where to begin with this..)

    Thats just great.. So there is no possible was to do this automatically in AS1?
    Thats just lameo. I'm thinking of purchasing this Flash knockoff so I can use AS3:
    http://3dfa.com/
    Does anyone know anything about this?

Maybe you are looking for

  • PLS-00801: internal error [74306] Help me!

    Hi, I have written some PL/SQL Application using Bulk Binding and PL/SQL Collection at Oracle 9.2.0.8 AIX But, I met the strange error message during compilation. PLS-00801: internal error [74306|http://forums.oracle.com/forums/] I tried to search Go

  • As3.0 upload option

    hi we need to upload file option in as3.0. (.jpg,  gif, swf, ect...) . How to create this option. this upload file to  store in one folder. any refference. sample file. help me thanks

  • Forms 6i/9i with Oracle 9i in Character mode

    I want to check to deploy forms 6i/9i with Oracle 9i OS will be IBM-AIX. Whether is it possible to execute the forms on server itself in character mode ? Thakns Dilip Patel.

  • IPTV 3.4 Allow access to content without password

    Well 3.4 has made up the problems with lack of security in 3.2 only to make it essentially that now enter a password while accessing the server. My problem is I want web pages using the plugin to access the sdp files from the download directory witho

  • Doubt in plsql

    hai... i have a table like this... PROCEDURE SHOW_UNSTRUCTURED_EDIT Argument Name Type In/Out Default? P_TEMPLATE_ID NUMBER IN DEFAULT P_TEMPLATE_NAME VARCHAR2 IN DEFAULT PROCEDURE SHOW_UNSTRUCTURED_PREVIEW Argument Name Type In/Out Default? --------