When to wrap a function around blocks of code (best practice \ style question)

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Daniel Krebs Daniel Krebs 2 weeks, 6 days ago.

  • Author
    Posts
  • #70038
    Profile photo of Joey Piccola
    Joey Piccola
    Participant

    I have a script that wraps a lot of error handling around existing cmdlets (Set-VM, Start-VM, Invoke-VMScript, etc). Would it be best to wrap parameterized functions around all these try\catch blocks so that my parent script doesn't look so terrible? This would tuck all my write-verbose, my action cmdlets, try\catch into a single line. Below is an example of the try\catch blocks. These blocks are nested in two foreach loops, hints the continue.

    On a related note, I am just now remembering that if I tuck all this as functions in my module then I loose the verbose output...

    Thanks for the help.

  • #70056
    Profile photo of Daniel Krebs
    Daniel Krebs
    Moderator

    I would wrap these distinct steps into parameterised functions to clean up the code. To handle the scenario where you want to skip the remaining steps with 'continue' your parameterised functions should return a status probably in the form of a boolean (true/false) you can test for with "if (-not (verb-noun @splat)) { continue }" or "if (! verb-noun @splat) { continue }".

    If VerbosePreference is set to Continue before invoking your functions in the module they should inherit the value and still out verbose messages.

    I hope above makes sense.

    #Daniel

You must be logged in to reply to this topic.