How to save complex PowerShell variables as CliXML instead of Newtonsoft.Json.Linq.JProperty in the Azure Automation
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
This makes retrieving the content of the variables quite unfriendly if you are not familiar with this Newtonsoft.Json.Linq.JProperty
.
Solution
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:
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