0
当一个对象传入函数时,它似乎失去了与它关联的NoteProperty
类型的任何属性。对象传递到函数时丢失的对象属性
简单的试验可以再现这种行为(下面的代码),这导致以下输出 -
检查的功能外 -
属性存在。
检查功能内部 -
属性不存在。
是否有人能够解释为什么PowerShell在此庄园中行事,以及我如何解决它以确保我添加的成员正按预期传递给函数?
代码重现以上水煤浆
function Out-Object
{
param(
[parameter(Mandatory=$true)]
[object[]]$Object
)
Write-Output "Checking inside of function -"
if (Get-Member -InputObject $Object -Name "PropertyOne" -MemberType "NoteProperty") {
Write-Output " Property exists."
} else {
Write-Output " Property does not exist."
}
}
$newObject = New-Object -TypeName PSCustomObject
$newObject | Add-Member -NotePropertyName "PropertyOne" -NotePropertyValue "ValueOne"
Write-Output "Checking outside of function -"
if (Get-Member -InputObject $newObject -Name "PropertyOne" -MemberType "NoteProperty") {
Write-Output " Property exists."
} else {
Write-Output " Property does not exist."
}
Out-Object $newObject
'[[对象] $ Object'需要指数$对象 - >' [对象] $ Object'。该属性不会丢失,但是您将该对象包装在一个数组中,然后检查该数组是否具有其嵌套对象的属性(它没有)。 –
或者使用函数的begin-process-end结构,分别为'$ object'中的每个对象运行进程代码,从而无需额外的麻烦即可访问其所有属性。 – Vesper