首页 > 解决方案 > PowerShell:如何只返回一个 [PSCustomObject] 而不是其中包含其他内容的数组?

问题描述

我有一个返回[PSCustomObject]. 这是在 2 个 cmdlet 深处完成的。在每次返回时,它都会添加另一个东西,然后它不是返回,[PSCustomObject]而是返回一个包含 3 个项目的数组。该对象具有字符串属性,并且在每个级别都为它们添加了另一个前导空格。

我只想返回 [PSCustomObject]no 数组。这个怎么做 ?

从最后一个 cmdlet 返回的对象

$ident
LocalTime           UtcTime              Data                             
---------           -------              ----                             
5/6/2021 3:43:35 PM 5/6/2021 10:43:35 PM New-NodeIdentifier  "4"          
5/6/2021 3:43:35 PM 5/6/2021 10:43:35 PM New-NodeGenerationIdentifier  "4"

$ident.Count
3

2 method deap , 2 leading spaces 
"$($ident.String)"
"  4"

"$($ident[2].String)"
"4"

功能

Function New-NodeIdentifier{
 [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [String]$Identifier,
        [Switch]$NoCmdletEntryOutput
    )
    Begin{}
    
        Process{


        Start-CmdletEntry "New-NodeIdentifier  `"$($Identifier)`"" -NoCmdletEntryOutput:$NoCmdletEntryOutput

        #determin identifyer type 


        $l = $Identifier.split(".")

        [double]$OutNumber = $null
        $IsGen = $true
        foreach( $c in $l ) {
            Write-Host $c
            if(-not [double]::TryParse($c,[ref]$OutNumber)) {
                $IsGen = $false
            }
        }

        # create the indentifier 

        if($IsGen) {

            $ni =  New-NodeGenerationIdentifier -Generation $Identifier

            write-host "nni `"$($ni.String)`" type $($ni.GetType())"

            return $ni

        } else {

            $ni  =  New-NodeHwSkuIdentifier -HwSku $Identifier

            write-host "nni `"$($ni.String)`" type $($ni.GetType())"

            return $ni
        }

      
     }
   
   End{}
}

Function New-NodeGenerationIdentifier{
 [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [String]$Generation,
        [Switch]$NoCmdletEntryOutput
    )
    Begin{}

       
    Process{

         Start-CmdletEntry "New-NodeGenerationIdentifier  `"$($Generation)`"" -NoCmdletEntryOutput:$NoCmdletEntryOutput

         $vmi = [PSCustomObject]@{
                Generation   ="$($Generation)"
                Type         ='Generation'
                String       ="$($Generation)"
                }
         
         write-host "nngi `"$($vmi.String)`" type $($vmi.GetType())"

         return $vmi 

     }
   
   End{}
}

标签: powershell

解决方案


通过 mklement0 的链接,我想通了。所以是的,这是PowerShell 隐式输出行为的受害者。我的 Start-CmdletEntry 返回了一些东西,然后成为返回负载的一部分。


推荐阅读