通过调用表达式传递哈希表时发生Powershell错误
我有以下Powershell脚本片段,正在使用Invoke Expression cmdlet调用另一个Powershell脚本:通过调用表达式传递哈希表时发生Powershell错误,powershell,Powershell,我有以下Powershell脚本片段,正在使用Invoke Expression cmdlet调用另一个Powershell脚本: $headers=@{} $headers.Add("Authorization", "Basic $encodedCredentials") $ScriptPath = Split-Path $MyInvocation.InvocationName $args = @() $args += ("-arg1", $arg1) $args += ("-arg2",
$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")
$ScriptPath = Split-Path $MyInvocation.InvocationName
$args = @()
$args += ("-arg1", $arg1)
$args += ("-arg2", $arg2)
$args += ("-headers", $headers)
$cmd = "$ScriptPath\subScript.ps1"
Invoke-Expression "$cmd $args"
subScript.ps1中的参数列表如下:
param
(
[Parameter(Mandatory=$true)]
[String]$arg1 = $(throw "arg1 is mandatory, please provide a value."),
[Parameter(Mandatory=$true)]
[String]$arg2 = $(throw "arg2 is mandatory, please provide a value."),
[Parameter(Mandatory=$true)]
$headers = $(throw "headers is mandatory, please provide a value.")
)
我已经验证了当我删除两个脚本中的“$headers”参数时,第二个脚本是否执行。再次添加后,我会收到以下错误消息:
调用RestMethod:无法绑定参数“Headers”。无法转换
类型为“System.String”的“System.Collections.Hashtable”值
键入“System.Collections.IDictionary”
我尝试添加“System.Collections.Hashtable”和“Hashtable”作为subScript.ps1中的参数类型,但这只会将错误消息更改为:
无法处理参数“headers”上的参数转换。不能
转换类型的“System.Collections.Hashtable”值
“System.String”输入“System.Collections.Hashtable”
如何实现这一点?不要使用
调用表达式(这是不安全的,只适用于字符串输入),也不要(重新)使用$args
(这是一个自动变量)
将哈希表改为:
$headers=@{}
$headers.Add(“授权”、“基本$encodedCredentials”)
$ScriptPath=拆分路径$MyInvocation.InvocationName
$params=@{
“arg1”=$arg1
“arg2”=$arg2
“headers”=$headers
}
$cmd=“$ScriptPath\subScript.ps1”
#使用`&`call运算符调用下一个脚本
&$cmd@params
有关更多信息,请参阅