【问题标题】:Powershell v2 does not return the object of a functionPowershell v2 不返回函数的对象
【发布时间】:2014-01-18 19:26:00
【问题描述】:

我有一个函数可以测试一个或多个路径是否有效以及它们是否存在。现在我创建了一个包含多个数组的自定义 PSObject,并希望该函数返回该对象。但它似乎只返回一个数组而不是原始的自定义对象。 Powershell ISE 的调试器显示该对象存在于函数中。我做错了什么?

这是我的代码

function Validate-Path
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param
    (
    [Parameter(Mandatory = $true)]
    [Array]$Inputpaths
    )
        $Ispathvalid=test-path $Inputpaths -IsValid
        $Validpaths=@()
        $Invalidpaths=@()

        $counter=0
        foreach ($item in $Ispathvalid)
        {
            if($Ispathvalid[$counter] -eq $true)
            {
                $Validpaths+=$Inputpaths[$counter] 
            }
            else
            {
                $Invalidpaths+=$Inputpaths[$counter] 
            }
            $counter++

        }

        $Doespathexist=test-path $Validpaths
        $Testvalue=$true
        $Existingpaths=@()
        $NonExistingpaths=@()
        $counter=0
        foreach ($item in $Validpaths)
        {
            if($Doespathexist[$counter] -eq $true)
            {
                $Existingpaths+=$Validpaths[$counter] 
            }
            else
            {
                $NonExistingpaths+=$Validpaths[$counter]
            }
            $counter++

        }

        $object = New-Object  PSObject 
        $object | Add-Member -MemberType NoteProperty -Name Existingpaths -Value $Existingpaths
        $object | Add-Member -MemberType NoteProperty -Name NonExistingpaths -Value $NonExistingpaths
        $object | Add-Member -MemberType NoteProperty -Name Validpaths -Value $Validpaths
        $object | Add-Member -MemberType NoteProperty -Name Invalidpaths -Value $Invalidpaths

        return $object
}

【问题讨论】:

  • 代码对我有用。 $PSVersionTable 在您的系统上的输出是什么。
  • 也适合我。你能说明你是如何调用它的,以及产生的输出吗?

标签: function object powershell return


【解决方案1】:

使用PSCustomObject 代替PSObject

改变这一行:

$object = New-Object  PSObject 

到这里:

$object = New-Object -TypeName PSCustomObject;

【讨论】:

  • 这应该没什么区别,因为PSObject 只是PSCustomObject 的缩写。
猜你喜欢
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2011-12-28
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多