0

我有一个 PSObject 集合,我想对其进行迭代,设置组成成员的属性。我设置了一个for循环并通过引用一个函数来传递当前对象,但不知道如何访问对象属性。例子:

function create-object {
    $foo = new-object -TypeName PSObject -Prop `
        @{
            "p1" = $null
            "p2" = $null
        }
    $foo
}

$objCol = @()

foreach ($k in (1 .. 3)){$objCol += create-object} 

for ($i=0;$i -le $objCol.Length;$i++) {
    Write-Host "hi"
    reftest ([ref]$objCol[$i])
}

function reftest([ref]$input)
{
    $input.p1.value="property1"
}
$objCol

... 返回Property 'p1' cannot be found on this object-- 如何通过引用从函数中设置 $object.p1?

4

1 回答 1

2

正如 Christian 所指出的,我已经重新格式化了您的示例,也将 of 更改为$input不同的名称, 。$arg以下作品:

function create-object {
    $foo = new-object PSObject -Property @{
        "p1" = $null
        "p2" = $null
    }
    $foo
}

function reftest($arg)
{
    $arg.p1="property1"
}

$objCol = @()

(1..3) | % {$objCol += create-object} 

for ($i=0;$i -lt $objCol.Length;$i++) {
    reftest $objCol[$i]
}

$objCol
于 2012-12-25T07:58:21.367 回答