2

我一直在研究一些 PowerShell 代码,并试图使其尽可能可读(PowerShell 非常擅长的东西)。虽然我们有一个 Add-Member 函数和一个 Get-Member 函数,但没有相关的 Set-Member 函数。所以我开始为我的项目创建一个。但是,在函数本身(如下所示)中,它要求我使用以下行:

$_.$NotePropertyName = $NotePropertyValue

去工作。但是,我认为我应该使用这条线,但它不起作用:

$InputObject.$NotePropertyName = $NotePropertyValue

为什么会有这样的反应?

Function Set-Member
{
    [CmdletBinding(DefaultParameterSetName='Message')]
    param(
        [Parameter(ParameterSetName='Message', Position=0,  ValueFromPipeline=$true)] [object[]]$InputObject,
        [Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyName,
        [Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyValue
    )
    $strInitialValue = $InputObject.($NotePropertyName)  # Get the value of the property FirstName
                                                         # for the current object in the pipe
    $_.$NotePropertyName = $NotePropertyValue
}


$objTest = [PSCustomObject]@ {
    FirstName = "Bob"
    LastName = "White"
}

$objTest | ForEach-Object {
    $_ | Set-Member -NotePropertyName "FirstName" -NotePropertyValue "Joe"
    $_      # Push the object back out the pipe
}

$objTest | ForEach-Object {
    $_ | Set-Member -NotePropertyName "FirstName" -NotePropertyValue "Bobby$($_.FirstName)"
    $_      # Push the object back out the pipe
}
4

1 回答 1

4

您将 $InputObject 参数定义为对象数组。您的函数中应该有一个for循环来迭代数组,而不是将其视为单个对象。或者将类型更改为[object]而不是[object[]].

由于您使用管道来调用函数,因此您应该使用函数的进程块,否则您只会看到管道中处理的最后一项。

Function Set-Member
{
    [CmdletBinding(DefaultParameterSetName='Message')]
    param(
        [Parameter(ParameterSetName='Message', Position=0,  ValueFromPipeline=$true)] [object[]]$InputObject,
        [Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyName,
        [Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyValue
    )
    process
    {
        foreach ($obj in $InputObject)
        {
            $strInitialValue = $obj.($NotePropertyName)  # Get the value of the property FirstName
                                                         # for the current object in the pipe
            $obj.$NotePropertyName = $NotePropertyValue
        }
    }
}
于 2013-05-15T19:02:29.550 回答