当一个objet被传递给一个函数时,它似乎丢失了与它关联的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
答案 0 :(得分:1)
正如安斯加所说,你将它视为对象外部函数中的数组。你可以改变
[object[]]$Object
到
[object]$Object
或者您需要索引函数中的$ object
if ( Get-Member -InputObject $Object[0] -Name "PropertyOne" -MemberType "NoteProperty" ) {