PowerShell Set-Member 函数和 $_ 的用法

Sco*_*t H 3 powershell powershell-3.0

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

$_.$NotePropertyName = $NotePropertyValue
Run Code Online (Sandbox Code Playgroud)

上班。但是,我认为我应该使用该行,但它不起作用:

$InputObject.$NotePropertyName = $NotePropertyValue
Run Code Online (Sandbox Code Playgroud)

为什么会有这样的反应呢?

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
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ens 5

您将 $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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)