如何使用对象引用创建工作powershell Add-Member?

时间:2017-06-16 11:11:51

标签: powershell

Add-Member[ref]引起了一些麻烦。它们不起作用: - (

代码:

function ObjPropAdd([ref]$obj, $name, $value)
{
    # Failed: object reference does not work
    $obj | Add-Member –MemberType NoteProperty –Name $name –Value $value
}

function ObjPropRemove([ref]$obj, $name)
{
    # Success: object reference is work
    $obj.value.PSObject.Properties.Remove($name)
}

$obj = [PsCustomObject]@{ var1 = 'val1'; var2 = 'val2' }
Write-Host ($obj | ConvertTo-Json)

$obj | Add-Member –MemberType NoteProperty –Name "var3" –Value "val3" # Success: Add-Member is works
Write-Host ($obj | ConvertTo-Json)

ObjPropAdd ([ref]$obj) "var4" "val4"    # Failed: object reference does not work
Write-Host ($obj | ConvertTo-Json)

ObjPropRemove ([ref]$obj) "var1"        # Success: object reference is works
Write-Host ($obj | ConvertTo-Json)

结果:

{
    "var1":  "val1",
    "var2":  "val2"
}
{
    "var1":  "val1",
    "var2":  "val2",
    "var3":  "val3"
}
{
    "var1":  "val1",
    "var2":  "val2",
    "var3":  "val3"
}
{
    "var2":  "val2",
    "var3":  "val3"
}

错过了我的变量var4

谢谢。

0 个答案:

没有答案