簡體   English   中英

PowerShell - 如何從數組中獲取 PsObject 屬性的值?

[英]PowerShell - How to get the value of PsObject property from an array?

編輯:改寫問題更清楚

這是工作代碼:

$arr = @(
    @('prop0','name0'),
    @('prop1','name1'),
    @('prop2','name2')
)

$obj = New-Object PsObject
foreach($innerArr in $arr)
{
    $obj | Add-Member -NotePropertyName $innerArr[0] -NotePropertyValue $null
}

$obj2 = New-Object PsObject
$count = 0
foreach($innerArr in $arr)
{
    $value = 'val' + $count
    $obj2 | Add-Member -NotePropertyName $innerArr[1] -NotePropertyValue $value
    $count ++
}

for($i=0; $i -lt $arr.Count; $i++)
{
    # This is what I want to consolidate into one line
    # {
    $prop_name = $arr[$i][1]
    $obj | Add-Member -NotePropertyName $arr[$i][1] -NotePropertyValue $obj2.$prop_name
    # }
}

如何在不將屬性名稱分配給$prop_name情況下執行此$prop_name

$obj的輸出應如下所示:

PS C:\> $obj
prop0 : 
prop1 : 
prop2 : 
name0 : val0
name1 : val1
name2 : val2

這將使您通過您出錯的部分:

$obj | Add-Member -NotePropertyName $arr[$i][1] -NotePropertyValue $obj2.PSObject.Properties.Item("name$i").value

問題是當 PSobject 不像數組時,您將其視為數組。 它更像是一本字典。

核心價值

核心價值

核心價值

由於沒有層次結構,您必須指定要查找的 Key。

如果我要這樣做,我會選擇類似的東西

$obj2arr = @($obj2.PSObject.Properties | %{$_})
for($i=0; $i -lt $arr.Count; $i++)
{
     $obj | Add-Member -NotePropertyName $arr[$i][1] -NotePropertyValue $obj2arr[$i].Value
}

將 PSObject 轉換為 Items 數組並拉取我要使用的屬性

自從我在這里回答以來,您的問題發生了一些變化,因此腳本已縮短

$arr = @(
    @('prop0','name0'),
    @('prop1','name1'),
    @('prop2','name2')
)
$obj = New-Object PsObject
$arr | %{ $obj | Add-Member -NotePropertyName $_[0] -NotePropertyValue $null}
$obj2 = New-Object PsObject
$count = 0
$arr | %{ $obj2 | Add-Member -NotePropertyName $_[1] -NotePropertyValue ('val' + $count); $count++}
$obj2arr = @($obj2.PSObject.Properties | %{$_})
$count = 0
$arr | foreach-object{$obj | Add-Member -NotePropertyName ($_)[1] -NotePropertyValue $obj2arr[$count].Value; $count++}
$obj

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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