在Powershell函数中处理管道和参数输入

low*_*teq 6 powershell

我对在一个月的午餐中学习PowerShell一书中看到的东西感到困惑.在第21章中,当作者讨论通过参数绑定或管道接受输入的函数时,他给出了两种模式.

第一个如下

function someworkerfunction {
# do some work
}
function Get-SomeWork {
   param ([string[]]$computername)
   BEGIN {
      $usedParameter = $False
      if($PSBoundParameters.ContainsKey('computername')) {
         $usedParameter = $True
      }   
   }
   PROCESS {
      if($usedParameter) {
         foreach($computer in $computername) {
            someworkerfunction -computername $comptuer
         }
      } else {
         someworkerfunction -comptuername $_
      }
   }

   END {}
}
Run Code Online (Sandbox Code Playgroud)

第二个是这样的

function someworkerfunction {
# do stuff
}
function Get-Work {
   [CmdletBinding()]
   param(
      [Parameter(Mandatory=$True,
      ValueFromPipelineByPropertyName=$True)]
      [Alias('host')]
      [string[]]$computername
   )
   BEGIN {}
   PROCESS {
      foreach($computer in $computername) {
         someworkerfunction -comptuername $computer
      }
   }
   END {}
}
Run Code Online (Sandbox Code Playgroud)

我知道第二个样本是标准的Powershell 2.0 Advanced功能.我的问题是Powershell 2.0对cmdletbinding指令的支持你是否想要使用第一个模式.这只是Powershell 1.0的遗产吗?基本上是有过使用PowerShell 2.0,当时候,我会想更动的第一图案,当第二图案是如此的干净多了.

任何见解将不胜感激.

谢谢.

And*_*ndi 3

如果您想在函数中处理管道输入,但不想添加所有参数属性或希望向后兼容,请使用cmdletbindingless 方式。

如果您想使用 PowerShell 脚本 cmdlet 的附加功能(例如参数属性、参数集等),请选择第二个。