gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:37:57 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com