0
votes

I have the following Powershell script snippet that is calling another Powershell script using the Invoke-Expression cmdlet:

$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"

The list of parameters in subScript.ps1 is as follows:

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.")
)

I have verified that the second script executes when I remove the "$headers" parameter in both scripts. Once I add it again I get the following error message:

Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to type "System.Collections.IDictionary".

I tried adding both "System.Collections.Hashtable" and "hashtable" as the type of the parameter in subScript.ps1 but that only changes the error message to:

Cannot process argument transformation on parameter 'headers'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to type "System.Collections.Hashtable".

How can this be accomplished?

1

1 Answers

1
votes

Don't use Invoke-Expression (it's unsafe and only works on string input) and don't (re-)use $args (it's an automatic variable)!

Use the hashtable for splatting your arguments instead:

$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")

$ScriptPath = Split-Path $MyInvocation.InvocationName
$params = @{
    "arg1" = $arg1
    "arg2" = $arg2
    "headers" = $headers
}
$cmd = "$ScriptPath\subScript.ps1"

# use the `&` call operator to invoke the next script
& $cmd @params

For more information see the about_Splatting helpfile