Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a function only for a catch block?

I have multiple try catch blocks and all of them are using the same catch block.

    try {   
        invoke-command -cn $host -Credential $cred -ScriptBlock {
        param($name)    
        statement...
        } -ArgumentList $name
        
    } catch {
        $formatstring = "{0} : {1}`n{2}`n" +
                    "    + CategoryInfo          : {3}`n" +
                    "    + FullyQualifiedErrorId : {4}`n"
        write-host ($formatstring)
        exit 1
    }

...

    try {   
    another statement...
        
    } catch {
        $formatstring = "{0} : {1}`n{2}`n" +
                    "    + CategoryInfo          : {3}`n" +
                    "    + FullyQualifiedErrorId : {4}`n"
        write-host ($formatstring)
        exit 1
    }

I want to ask if it is possible to create a function which has the catch block so that I can call and use the function instead of writing the same catch block multiple times.

I am using poweshell 5

like image 869
meallhour Avatar asked Dec 12 '25 22:12

meallhour


1 Answers

catch requires a literal { ... } block to follow it, but from inside that block you're free to call reusable code, such as a function, or, in the simplest case, a script block:

# Define a script block to use in multiple `catch` blocks.
$sb = {
  "[$_]" # echo the error message
}

# Two simple sample try / catch statements:

try {
  1 / 0
}
catch {
  . $sb # `. <script-block>` invokes the block directly in the current scope
}

try {
  Get-Item -NoSuchParam
}
catch {
  . $sb
}

Note: ., the dot-sourcing operator, is used to invoke the script block directly in the current scope, allowing you to directly modify that scope's variables. This makes the script block behave as if it were used directly as the catch black.

If, by contrast, you want to execute the script block in a child scope, use &, the call operator.

like image 133
mklement0 Avatar answered Dec 15 '25 11:12

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!