Saturday, June 5, 2021

 Improving resiliency and predictability of Powershell automation scripts.

PowerShell is a convenient scripting language for interactive use and automations. There are several features available to use with the automation. These include the following:

- The use of common parameters called –ErrorAction and –ErrorVariables

- The use of try-catch-finally 

- The use of staged or pipelined operations

- The use of state persistence for rollback and recovery

As we discuss these options, it may be opportune to call out the requirements first. Scripts generally have more than one cmdlet invocations and they need to be able to revert to the original starting state if any of the steps fail. Certain exceptions might be tolerated others might be fatal and these would need to be aligned with the overall starting and end states for the script. The use case for evaluating the options above remains one where we can revert to the starting state before the execution of the script.

The ErrorAction is a common parameter across all cmdlets. It can have one of four values - Stop, Continue, SilentlyContinue and Inquire. The error variable stores errors from the command during processing. This is atleast helpful to halt the processing when a step cannot be completed but the changes may have already occurred that need to be undone. Testing for the error variable and taking the appropriate steps would be one option to address the case.

The try-catch-finally is a useful construct across both programming as well as scripting. The catch handler allows the appropriate handling of the rollback. Additionally, more than one catch can be used based on the type of the exception that is handled. 

The staged or the pipelined operations involves leaving more than one intermediate results so the reversals can be worked out from one known result to another. This is easily determined because the path between the stages is like an automata. It is easy to go back and forth between stages or progressively cycle through the stages.

The last option does not involve the interim results of execution but relies on states because they are smaller and easier to store in the form of variables rather than have all the information of the starting, ending or intermediate results or processing actions. Testing for a state variable alone is sufficient to determine the corrective action. For example, a work item can transition from initialized, in progress, completed or error and the next retry can be triggered via reverting to the initialized.

All these options can be tried out for the cheapest and most convenient one  to use in the application and they can perform deterministically each time.


No comments:

Post a Comment