Powershell中的通用参数

时间:2014-06-26 13:43:07

标签: powershell generics pipeline

在powershell中,有没有办法指定参数是通用的?基本上,我写的函数并不关心你交给它的类型,因为它在技术上适用于所有对象,但如果我指定[object[]]作为参数类型,则对象会丢失类型信息可能会或可能不会被其他CmdLets正确处理。

function Pack-Objects{
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [object[]]$InputObjects
    )

    BEGIN{
        $OutputObjects = New-Object System.Collections.ArrayList($null)
    }PROCESS{
        $OutputObjects.Add($_) | Out-Null
    }END{
        Write-Verbose "Passing off $($OutputObjects.Count) objects downstream" 
        return ,$OutputObjects.ToArray()
    }
}

例如,如果我运行1,2,3 | Pack-Objects | Get-Member,则返回的类型为System.Object[]。我想要它,如果我传递整数,它给我一个整数数组;字符串和字符串数组;等等。

1 个答案:

答案 0 :(得分:0)

我不明白为什么你需要它,但这应该做你想要的:

 [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        $InputObjects
    )    
        BEGIN{
                $script:i = 0
                $script:OutputObjects = New-Object System.Collections.ArrayList($null)
              }        
        PROCESS{
                foreach ( $_ in $InputObjects)
                { 
                  $script:t = $_.gettype() | select -expa name
                  if ( $i -gt 0 )
                  {
                     if ( $ts -notmatch $t ){"types are differents!!";break}
                  }

                $ts = $t
                $i++
                $OutputObjects.Add($_) | Out-Null
                }
               }        
       END{
            iex "[$t[]]`$OutputObjects = `$OutputObjects.toarray()"                    
            @(,$OutputObjects)
           }


PS C:\ps> ("q","d","e" | .\Pack-Objects.ps1).gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array    

PS C:\ps> (1,2,3 | .\Pack-Objects.ps1).gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32[]                                  System.Array

PS C:\ps> 1,2,3,"e" | .\Pack-Objects.ps1 
types are differents!!