PowerShell: Passing an ArrayList of Objects into another Script as an Argument
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error PowerShell: Passing an ArrayList of Objects into another Script as an Argument on this date .
I am trying to pass an ArrayList that contains objects into another PowerShell script to execute something further.
The error message that I am receiving is:
“Cannot process argument transformation on parameter ‘al’. Cannot convert the “System.Collections.Hashable System.Collections.Hashable System.Collections.Hashable” value of type “System.String” to type “System.Collections.ArrayList””
In script1.ps1:
$al = New-Object System.Collections.ArrayList ... $obj = @{"var1"="apple"; "var2"="banana"; "var3"="carrot";} $al.Add($obj) ... foreach ($i in $al) { $temp = $($i.var1) write-host "$temp" #outputs "apple" correctly } invoke-expression -Command "script2.ps1 -al '$al'"
In script2.ps1:
param ([System.Collections.ArrayList]$al) ... foreach ($i in $al) { $temp = $($i.var1) write-host "$temp" #error message }
Answer
For a reason that I’m not familiar with, Invoke-Expression
is converting your ArrayList to a HashTable. If you really need an ArrayList in script2.ps1, you can make $al
a global variable (see below).
Updated script1.ps1
$al = New-Object System.Collections.ArrayList $obj = @{"var1" = "apple"; "var2" = "banana"; "var3" = "carrot"; } $al.Add($obj) foreach ($i in $al) { $temp = $($i.var1) write-host "$temp" } $Global:al = $al invoke-expression -Command "$PSScriptRootscript2.ps1"
Updated script2.ps1
param() $Global:al.GetType().FullName foreach ($i in $Global:al) { $temp = $($i.var1) write-host "$temp" }