powershell - splatting 时使用哈希表作为参数?

标签 powershell hashtable start-job

我正在尝试使用 Start-Job 来启动一个新的 Powershell 脚本。新脚本有几个参数(有些是可选的,有些不是),所以我想制作一个哈希表并将它们拼凑起来。然而,这些参数之一本身就是一个哈希表。我正在尝试像这样开始工作:

$MyStringParam = "string1"
$MyHashParam = @{}
$MyHashParam.Add("Key1", "hashvalue1")

$arguments = @{MyStringParam=$MyStringParam;MyHashParam=$MyHashParam}

Start-Job -Name "MyJob" -ScriptBlock ([scriptblock]::create("C:\myscript.ps1 $(&{$args} @arguments)"))

于是我在新工作中遇到了这个错误:
Cannot process argument transformation on parameter 'arguments'. 
Cannot convert the "System.Collections.Hashtable" value of 
type "System.String" to type "System.Collections.Hashtable".

看起来它正在将我想作为哈希表传入的值作为字符串处理。对于我的生活,我不知道如何解决这个问题。任何人都可以帮忙吗?

最佳答案

您需要将该变量作为脚本块的参数传递到脚本块中,然后将该参数传递给您的第二个脚本。像这样的事情应该适合你:

Start-Job -Name "MyJob" -ScriptBlock {Param($PassedArgs);& "C:\myscript.ps1" @PassedArgs} -ArgumentList $Arguments

我创建了以下脚本并将其保存到 C:\Temp\TestScript.ps1
Param(
    [String]$InString,
    [HashTable]$InHash
)
ForEach($Key in $InHash.keys){
    [pscustomobject]@{'String'=$InString;'HashKey'=$Key;'HashValue'=$InHash[$Key]}
}

然后我运行了以下命令:
$MyString = "Hello World"
$MyHash = @{}
$MyHash.Add("Green","Apple")
$MyHash.Add("Yellow","Banana")
$MyHash.Add("Purple","Grapes")

$Arguments = @{'InString'=$MyString;'InHash'=$MyHash}

$MyJob = Start-Job -scriptblock {Param($MyArgs);& "C:\Temp\testscript.ps1" @MyArgs} -Name "MyJob" -ArgumentList $Arguments | Wait-Job | Receive-Job
Remove-Job -Name 'MyJob'
$MyJob | Select * -ExcludeProperty RunspaceId | Format-Table

它产生了预期的结果:
String                               HashKey                              HashValue                          
------                               -------                              ---------                          
Hello World                          Yellow                               Banana                             
Hello World                          Green                                Apple                              
Hello World                          Purple                               Grapes 

运行作业的过程将向返回的任何对象添加 RunspaceId 属性,这就是我必须排除它的原因。

关于powershell - splatting 时使用哈希表作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29952468/

相关文章:

javascript - 如何删除 Google Chrome 中的 Stackoverflow Cookie 和证书?

powershell - 怎么回声$?工作?

c++ - std::unordered_map 如何确定哈希表中特定键的位置?

c - 稀疏多维数组占用巨大空间-哈希表更好吗?

powershell - 如何从 Start-Job 调用脚本中的 powershell 函数?

powershell - PowerShell:Start-Job -scriptblock多行脚本 block ?

带有字符串数组的powershell函数开关参数

haskell - 对HashTable的性能问题感到好奇

powershell - 我可以将PowerShell 'Start-Job'设置为低优先级吗?

powershell - 如何以编程方式从 Azure AD 库添加应用程序