Use hashtable as parameter when splatting?
I am trying to use Start-Job to start a new Powershell script. The new script has several parameters (some are optional, some are not), so I want to create a hash table and split them. However, one of these parameters is itself a hash table. I am trying to get started like this:
$MyStringParam = "string1"
$MyHashParam = @{}
$MyHashParam.Add("Key1", "hashvalue1")
$arguments = @{MyStringParam=$MyStringParam;MyHashParam=$MyHashParam}
Start-Job -Name "MyJob" -ScriptBlock ([scriptblock]::create("C:\myscript.ps1 $(&{$args} @arguments)"))
After which I get this error in a new job:
Cannot process argument transformation on parameter 'arguments'.
Cannot convert the "System.Collections.Hashtable" value of
type "System.String" to type "System.Collections.Hashtable".
It looks like it is handling the value I want to pass as a hash table as a string. For life, I can't figure out how to get around this. Can anyone please help?
source to share
You will need to pass the variable in the scriptblock as a parameter to scriptblock, and then pass that parameter to the second script. Something like this should work for you:
Start-Job -Name "MyJob" -ScriptBlock {Param($PassedArgs);& "C:\myscript.ps1" @PassedArgs} -ArgumentList $Arguments
I created the following script and saved it to C: \ Temp \ TestScript.ps1
Param(
[String]$InString,
[HashTable]$InHash
)
ForEach($Key in $InHash.keys){
[pscustomobject]@{'String'=$InString;'HashKey'=$Key;'HashValue'=$InHash[$Key]}
}
Then I did the following:
$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
He gave the expected results:
String HashKey HashValue
------ ------- ---------
Hello World Yellow Banana
Hello World Green Apple
Hello World Purple Grapes
The job process will add the RunspaceId property to any returned objects, so I had to exclude that.
source to share