Nesting try-catch-finally

A try-catch-finally statement can be nested beneath another. This is most appropriate when a different approach is required by a smaller section of code.

A script perform setup actions, then working on a number of objects in a loop is a good example of one that might require more than one try-catch statement. The script should terminate cleanly if something goes wrong during setup, but it might only notify if an error occurs within the loop.

The following functions can be used as a working example of such a script. The setup actions might include connecting to a management server of some kind:

function Connect-Server {} 

Once the connection is established, a set of objects might be retrieved:

function Get-ManagementObject { 
    1..10 | ForEach-Object { 
[PSCustomObject]@{ Name = $_; Property = "Value$_" } 
    } 
} 

The Set filter accepts an input pipeline and changes a value on the object:

filterSet-ManagementObject { 
    [CmdletBinding()] 
    param ( 
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)] 
        $InputObject, 
 
$Property 
    )      
           
    $InputObject.Property = $Property 
} 

The following script uses the preceding functions. If a terminating error is raised during either the Connect or Get commands, the script will stop. If a terminating error is raised during Set, the script writes about the error and moves onto the next object:

try { 
    Connect-Server 
Get-ManagementObject | ForEach-Object { 
        try {     
            $_ | Set-ManagementObject -Property 'NewValue' 
        } catch { 
            Write-Error -ErrorRecord $_ 
        } finally { 
            $_ 
        }    
    }     
} catch { 
    throw
}

Changing individual functions to throw errors will show how each block triggers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.192