简体   繁体   中英

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

Edit : Rephrasing question to be more clear

Here is the working code:

$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
    # }
}

How do I do this without assigning the name of the property to $prop_name ?

The output of $obj should look like this:

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

This will get you past the part you are erroring on :

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

The issue is your treating the PSobject like a array when it doesnt act like a array. Its more along the lines of a dictionary.

Key : Value

Key : Value

Key : Value

Since there is no hierarchy you have to specify which Key you are looking for.

If I was going to do it i would go with something like

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

Turning the PSObject into an array of Items and puling the property I want to use

Since your question has changed a little since i answered here is the script shortened

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM