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
。
谢谢。