Building a better DSC script

Premier Developer

Premier

App Dev Manager Mark Pazicni strives to build a better DSC script.


For those people that want to build a better DSC script, one that checks for most conditions and wants to keep their custom scripts from failing with no error handling, check out these recommendations.

When writing a custom script in DSC, it comes down to PowerShell and how much you can ensure that you check for each situation in your script. You also need a way to verbosely write out what is happening in that script.

Step 1: Setting up a local log directory – If the log directory does not exist, create one, but if ones does exists, then you need ensure you have access to the directory. With a quick check of the ACL you can ensure that your script does not fail to process. Once you know the directory exists and you have access creating the log file is easy.

Step 2: Setting up a Transcript – this option records several system details as well as verbose message that written out of any command or comments made in code. This helps with debugging DSC’s that are failing on machines.

To force Write-Verbose cmdlet to display a status message regardless of value of the $VerbosePreferences variable, follow the Write-Verbose with a -Verbose. These status messages will not only show up in the Transcript file but also in the DSCExtensionHeader.XXX.log file. Otherwise Write-Verbose status message will only show up in the Transcript file.

Step 3: Wrapping your whole script in try…catch… finally block will ensure that your script running and all message are logged ensuring you can capture all status messaging in your script.

Lastly one other useful trick in writing better DSC scripts to create custom .NET code snippets that you can add to this script when necessary to do simple functions done in .NET. In this example we are overriding the base web client to add a timeout value so that if our download request does not complete with a specific time the script can be abort an easy find exception can be logged.

Additional Resources:

Azure Automation State Configuration Overview – https://docs.microsoft.com/en-us/azure/automation/automation-dsc-overview

Forward Azure Automation State Configuration reporting data to Azure Monitor logs – https://docs.microsoft.com/en-us/azure/automation/automation-dsc-diagnostics

Premier Developer
Premier Developer

Premier Support for Developers

Follow Premier   

0 comments

    Leave a comment