PowerShell Set-Member功能和$ _的用法

问题描述 投票:1回答:1

我一直在研究一些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
}
powershell powershell-v3.0
1个回答
3
投票

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

由于您使用管道调用该函数,您应该使用process block of the function,否则您将只看到管道中的最后一项处理。

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
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.