You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Start-AzureRmAutomationRunbook向Azure子Runbook传递哈希表?

问题分析与解决方案

咱们先拆解你遇到的异常:你看到Result1和Result2输出System.Collections.Hashtable,但在InlineScript里遍历的时候却得到了String类型的结果——这说明传递给test2的根本不是哈希表,而是字符串"System.Collections.Hashtable",再加上Workflow的序列化机制添了点小麻烦,才导致了后续的异常输出。

问题根源

  1. 错误的字符串转换:在test1的代码里,你用双引号把哈希表包裹成了字符串:
    $parameterHash = @{"Hash"="$Hash"}
    
    当你写"$Hash"时,PowerShell会自动把哈希表对象转换成它的默认字符串表示(也就是类型名称System.Collections.Hashtable),所以test2的$Hash参数收到的只是这个字符串,而非原始哈希表。
  2. Workflow序列化限制:Azure Automation的Workflow Runbook之间传递复杂对象(比如哈希表)时,Workflow的序列化机制会把对象转成PSObject,直接传递容易丢失原有的类型信息。

正确的传递方式

我们分两步修正这个问题:

1. 修改test1:用JSON序列化传递哈希表

把哈希表转成JSON字符串再传递,既能避免类型丢失,又能绕过Workflow的序列化限制:

workflow test1 {
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
    
    $Hash = @{"ping"="pong"}
    # 将哈希表序列化为JSON字符串,保留完整结构
    $hashJson = $Hash | ConvertTo-Json -Compress
    $parameterHash = @{"HashJson" = $hashJson}
    
    Start-AzureRmAutomationRunbook `
        -ResourceGroupName "rg1" `
        -AutomationAccountName "ac1" `
        -Name "test2" `
        -Parameters $parameterHash
}

2. 修改test2:反序列化JSON还原哈希表

在test2里接收JSON字符串,再转成真正的哈希表进行处理:

workflow test2 {
    Param (
        [string]$HashJson  # 接收JSON字符串,而非Object类型
    )
    
    # 把JSON字符串还原为哈希表
    $Hash = $HashJson | ConvertFrom-Json -AsHashtable
    
    "Result1:" $Hash
    InlineScript {
        $Hash = $using:Hash
        "Result2:" $Hash
        "Result3:"
        foreach ($h in $Hash.GetEnumerator()) {
            Write-Host "$($h.Name): $($h.Value)"
            "Result4:"
            $HashType = $Hash.GetType()
            $HashType
        }
    }
}

补充说明(兼容旧环境)

如果你的Azure Automation环境不支持ConvertFrom-Json -AsHashtable参数(PowerShell 6+才支持,当前沙箱已默认支持),可以用手动转换的方式:

$Hash = $HashJson | ConvertFrom-Json
$hashTable = @{}
foreach ($property in $Hash.PSObject.Properties) {
    $hashTable[$property.Name] = $property.Value
}

修改完成后,test2的输出会符合预期:

Result1: {[ping, pong]}
Result2: {[ping, pong]}
Result3:
ping: pong
Result4:
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

内容的提问来源于stack exchange,提问作者Chris2005

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:16:24