[英]PowerShell: Passing an ArrayList of Objects into another Script as an Argument
我正在尝试将包含对象的 ArrayList 传递到另一个 PowerShell 脚本中以进一步执行某些操作。
我收到的错误消息是:
"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""
在 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'"
在 script2.ps1 中:
param ([System.Collections.ArrayList]$al)
...
foreach ($i in $al) {
$temp = $($i.var1)
write-host "$temp" #error message
}
由于我不熟悉的原因, Invoke-Expression
正在将您的 ArrayList 转换为 HashTable。 如果您确实需要 script2.ps1 中的 ArrayList,您可以将$al
设为全局变量(见下文)。
更新了 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 "$PSScriptRoot\script2.ps1"
更新了 script2.ps1
param()
$Global:al.GetType().FullName
foreach ($i in $Global:al) {
$temp = $($i.var1)
write-host "$temp"
}
您在 $obj 中创建的是一个哈希表。 没有必要将其放入您想要的数组列表中。 你应该能够做到这一点。
在脚本 1 中
$obj = @{"var1"="apple"; "var2"="banana"; "var3"="carrot"}
Write-Host $obj["var1"]
& .\script2.ps1 -ht $obj
脚本 2
Param (
[hashtable]$ht
)
Write-Host $ht["var1"]
ArrayList 不会用于键值对。
[System.Collections.ArrayList]$al = "apple","banana","carrot"
$al.Add("orange")
部分问题是您不需要在此处在变量周围添加引号,它将$al
转换为字符串。
& .\script2.ps1 -al $al
你应该决定什么是最适合这项工作的,字典或列表。 多年来,到处都在讨论它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.