如何将哈希表传递给scriptblock?

时间:2016-04-05 12:57:00

标签: powershell

我试图将哈希表传递给像这样的脚本块,其中$arg3是我的哈希表。然而,它失败了。我该如何以正确的方式做到这一点?

它似乎没有将任何内容传递给脚本块。

$commandParameters.ComputerName = $ComputerName

$commandParameters.ScriptBlock = {

        param(
            [Parameter()]
            [switch]$arg1 = $false,
            [Parameter()]
            [array]$arg2,
            [Parameter()]
            [hashtable]$arg3
        )
    enter code here
    Doing something here
}

Invoke-Command @commandParameters -ArgumentList $arg1, @($arg2), $arg3

=============================================== ==================

我自己找到了答案,这对我有用。这是我构建关联数组然后将其传递给脚本块的方法。

我不知道为什么,但我使用点符号($ hash.a.b)来引用函数中的哈希表并且它可以工作,但它不适用于脚本块。看起来我需要在脚本块中使用[](例如$ hash [a] [b])。

$compADGroups = @{}

foreach ( $adGroup in $adGroups ) {

    if ( $compADGroups.$computerNameGroup -eq $null ) {

        $compADGroups[$computerName] = @{}

        $compADGroups[$computerName]["Group"] = @{}

        $compADGroups[$computerName]["Group"] = $hashString
    }
}

$session = New-PSSession -ComputerName 'Computer1'

Invoke-Command -Session $session -ArgumentList $compADGroups -ScriptBlock { param($compADGroups) $compADGroups[$env:computername]["Group"]}

Get-PSSession | Remove-PSSession

1 个答案:

答案 0 :(得分:0)

确保您正确使用Invoke-Command

$ScriptBlock = {
param(
    [Parameter(Mandatory=$True, Position=1)]
    [hashtable]$myHashTable
)

    # Code here
}

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList ([hashtable]$hashtable)

如果为脚本块指定了某些参数,请确保您还描述了位置值,并且通常是否是必需的。如果您尝试将哈希表作为隐式定义的参数数组中的第二个参数传递,请编写脚本块,使其在该特定位置获取哈希表。

例如,

$ScriptBlock= {
    param(
        [Parameter(Position=2)] # Take note of the position you set here
        [hashtable]$myHashTable,
        [Parameter(Position=1)]
        [string]$myString,
        [Parameter(Position=3)]
        [int]$myInteger
    )

        # Do stuff
}

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList ($myString, $myHashTable, $myInteger);
                                                                      # ^ variable is in second position
相关问题