Skip to main content

Command Palette

Search for a command to run...

How to save complex PowerShell variables as CliXML instead of Newtonsoft.Json.Linq.JProperty in the Azure Automation

Updated
2 min read
O

I work as System Administrator for more than 15 years now and I love to make my life easier by automating work & personal stuff via PowerShell (even silly things like food recipes list generation).

Azure Automation Account has a handy feature to define (shared) Variables that can be used across all your Runbooks. What is not so nice at least for me was finding that complex objects like hashtables, arrays, psobjects, etc are stored as Newtonsoft.Json.Linq.JProperty

image.png

This makes retrieving the content of the variables quite unfriendly if you are not familiar with this Newtonsoft.Json.Linq.JProperty.


Solution

💥
Because of Runbook string variable size limitations, this approach is suitable only for variables of small size. To overcome this limitation check Create persistent Azure Automation Runbook variables using Azure Blob Storage

How to "solve" this? Save variables using old, and good Export-CliXML and then retrieve them using Import-CliXML 😉. If you do so, nothing will change for you when you try to work with the saved variable. The array will be still array, psobject will be still psobject, etc. But beware that you have to save the output of Export-CliXML as a string! Otherwise Azure will again use Newtonsoft.Json.Linq.JProperty to save the variable.

To make this easier I've created two proxy functions Set-AutomationVariable2 and Get-AutomationVariable2 (part of my AzureResourceStuff module).

Step by step

Import the required module to your Automation account

To be able to use my functions, you need to import the module AzureResourceStuff to your Automation account. You can do it manually or use New-AzureAutomationModule (check this for more details)

New-AzureAutomationModule -moduleName 'AzureResourceStuff' -resourceGroupName <resourceGroupName> -automationAccountName <automationAccountName>

Create a new Automation variable

Create a new, empty variable of a string type that will be used to store our results.

Save the output to the Automation variable

To save the output to the Automation variable use the function Set-AutomationVariable2 like this

How the variable will look like:

image.png

Retrieve the Automation variable content and convert it back

To retrieve variable content and convert it back to the original object use the function Get-AutomationVariable2 like this

Tip

Don't forget you have to authenticate to Azure before working with Automation variables!

Connect-AzAccount -Identity

More from this blog

D

Do it PowerShell way :)

78 posts

With over 15 years of experience as a system administrator, I have a passion for automating workflows using PowerShell. I believe in sharing my creations with the community. Why not, right? :)