我有以下Powershell脚本片段,该片段使用Invoke-Expression cmdlet调用另一个Powershell脚本:
$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”参数时,第二个脚本已执行。一旦再次添加它,我将收到以下错误消息:
Invoke-RestMethod:无法绑定参数'Headers'。无法转换将“ System.String”类型的“ System.Collections.Hashtable”值设置为键入“ System.Collections.IDictionary”。
我尝试将“ System.Collections.Hashtable”和“ hashtable”都添加为subScript.ps1中参数的类型,但这仅将错误消息更改为:
无法处理参数'header'上的参数转换。不能转换类型的“ System.Collections.Hashtable”值“ System.String”键入“ System.Collections.Hashtable”。
如何完成?
请勿使用Invoke-Expression
(这是不安全的,仅适用于字符串输入),请勿(重新)使用$args
(这是一个自动变量)!