Powershell v2函数返回System.Object []而不是PSCustomObject

时间:2014-04-22 16:23:12

标签: powershell powershell-v2.0

我正在尝试创建一个创建自定义对象但遇到异常行为的函数。如果您运行以下代码,您将找到此输出

function Test-CustomObject {
    function Create-CustomObject {

        $objProps = @{ 
            'property1' = 'Hello from property 1';
            'property2' = 'Hello from property 2';
        }

        $obj = New-Object -TypeName PSCustomObject -Prop $objProps

        $obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 1' } -Name Method1 -PassThru
        $obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 2' } -Name Method2 -PassThru

        write-host "in function: $obj"
        write-host "in function type: $($obj.GetType())"

        return $obj
    }

    $newObj = Create-CustomObject
    write-host "after function: $newObj"
    write-host "after function type: $($newObj.GetType())"
}

Test-CustomObject

节目输出:

in function: @{property1=Hello from property 1; property2=Hello from property 2}
in function type: System.Management.Automation.PSCustomObject
after function:
after function type: System.Object[]

有谁知道为什么返回的对象是System.Object []而不是PSCustomObject?

2 个答案:

答案 0 :(得分:6)

PowerShell返回未分配给函数变量的所有内容,而不仅仅是返回关键字后的语句。

在您的代码中,它还会添加此调用的结果:

$obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 1' } -Name Method1 -PassThru
$obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 2' } -Name Method2 -PassThru

返回功能。

为避免这种情况,您可以使用代码替换此行(只需添加调用结果的[void]强制转换):

[void]($obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 1' } -Name Method1 -PassThru)
[void]($obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 2' } -Name Method2 -PassThru)

之后它将按预期工作。

答案 1 :(得分:0)

对此问题Nick's answer的更新答案是将行为异常的命令分配给变量。特殊变量$null倾向于完美地填补这一点。

$null = $obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 1' } -Name Method1 -PassThru
$null = $obj | Add-Member -MemberType ScriptMethod -Value { return 'Hello from method 2' } -Name Method2 -PassThru

然后您的函数可以Return告诉您。