小编Sco*_*t H的帖子

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

我一直在研究一些 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"
    $_ …
Run Code Online (Sandbox Code Playgroud)

powershell powershell-3.0

3
推荐指数
1
解决办法
4675
查看次数

标签 统计

powershell ×1

powershell-3.0 ×1