簡體   English   中英

PowerShell:將對象的 ArrayList 作為參數傳遞到另一個腳本中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM