【问题标题】:Function [Hashtable[]] parameter that can come from pipeline or argument可以来自管道或参数的函数 [Hashtable[]] 参数
【发布时间】:2015-02-18 19:20:28
【问题描述】:

这是一个通过参数接受哈希表数组的函数:

function abc () {

    Param([Hashtable[]]$tables)

    $tables.count

}

使用示例:

PS C:\> abc -tables @{ a = 10 }, @{ b = 20 }, @{ c = 30 }
3

这是一个通过管道接受哈希表的函数:

function bcd () {

    Param([parameter(ValueFromPipeline=$true)][Hashtable]$table)

    $input.count

}

使用示例:

PS C:\> @{ a = 10 }, @{ b = 20 }, @{ c = 30 } | bcd
3

有没有办法定义可以通过参数或管道通过相同参数接受哈希表数组的函数? IE。可以通过上述两种方式调用的函数。请注意,我需要将整个哈希表数组放在一个变量中(因此在上面的 bcd 中使用了 $input)。

【问题讨论】:

    标签: arrays function powershell hashtable pipeline


    【解决方案1】:
    function bcd () {
    
        Param([parameter(ValueFromPipeline=$true)][Hashtable[]]$table)
    
        Begin {$tables= @()}
        Process {$tables += $table}
        End {$tables.count}
    
    }
    
    @{ a = 10 }, @{ b = 20 }, @{ c = 30 } | bcd
    bcd -table @{ a = 10 }, @{ b = 20 }, @{ c = 30 }
    
    3
    3
    

    【讨论】:

      【解决方案2】:

      这是我对双模式(管道和命令行)参数的首选结构:

      Function bcd () 
      {
          Param(
             [parameter(ValueFromPipeline = $true)]
             [Hashtable[]]$table
          )
      
          Process 
          {
              ForEach ($tab in $table) 
              {  
                # do something with the table
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-08-30
        • 2020-04-11
        • 2018-03-06
        • 2018-10-02
        • 1970-01-01
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多