Today I was implementing a snapshot/restore mechanism for virtual machines with the help of Azure Automation. After importing my script in Azure Automation, I encountered an error while invoking it. The message was: Unable to cast object of type 'System.String' to type 'System.Object[]'.

The problem

The script was running great from my workstation (I know, it works on my machine!). The problem started to occur when invoking the script from Azure Automation. I started by upgrading the Azure modules in the assets, which didn't help. I commented stuff out until I only got the parameters block declared, nothing else... Still failing, strange...

I started to search for this message error online, nothing.

I realized that the problem was with my [string[]] $AzureVM parameter declared like below:

param (    
 [Parameter(Mandatory)]
 [string]$ConnectionAssetName,
 [Parameter(Mandatory)]
 [string]$ServiceName,
 [Parameter(Mandatory)]
 [string[]]$AzureVM,
 [string]$VmExportConfigFolderPath = 'C:\ExportedVMs'
)

The solution

I stumble upon an article on the web (see References) that was saying the following:

If you want to be able to start your runbooks from the Azure Automation portal using the Start Runbook wizard UI then keep these things in mind about input parameters:

  • The wizard UI allows you to input values for runbook parameters that can be represented by number, string, datetime, switch, boolean, Azure Automation credential asset name, JSON array, or JSON object.

  • If a runbook has a parameter with a default value, this default value will appear in the UI; you can choose to use this value or change it.

  • If a runbook parameter takes an [array] or [object] type, then these must be passed in JSON format in the start runbook dialog. For example:

  • A parameter of type [object] that expects a property bag can be passed in the UI with a JSON string formatted like this: {"StringParam":"Joe","IntParam":42,"BoolParam":true}.

  • A parameter of type [array] can be input with a JSON string formatted like this: ["Joe",42,true].

That's it, that was my error. I was writing my string value as a regular string and not in a JSON notation.

I changed the value for this parameter in the UI from vmName to ['vmName'] and it started to work.

Hope it helps you save some debugging time.

References