在 Powershell 函数中处理管道和参数输入 [英] Handling pipeline and parameter input in a Powershell function

查看:53
本文介绍了在 Powershell 函数中处理管道和参数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm confused about something I saw in the book Learn PowerShell in a Month of lunches. In chapter 21 when the author discusses functions that accept input via parameter binding or the pipeline he gives two patterns.

第一个如下

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 {}
}

第二个这样

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 {}
}

我知道第二个示例是标准的 Powershell 2.0 Advanced 函数.我的问题是 Powershell 2.0 支持 cmdletbinding 指令,你会想要使用第一个模式.这只是 Powershell 1.0 的遗产吗?基本上,在使用 Powershell 2.0 时,我想在第一个模式下搞砸,而第二个模式要干净得多.

I know the second sample is a standard Powershell 2.0 Advanced function. My question is with Powershell 2.0 support for the cmdletbinding directive would you ever want to use the first pattern. Is that just a legacy from Powershell 1.0? Basically is there ever a time when using Powershell 2.0 that I would want to mess around with the first pattern, when the second pattern is so much cleaner.

任何见解将不胜感激.

谢谢.

推荐答案

如果您想在函数中处理管道输入但不想添加所有参数属性或想向后兼容,请使用 cmdletbinding更少的方式.

If you want to process pipeline input in your function but don't want to add all the parameter attributes or want backwards compatibility go with the cmdletbindingless way.

如果您想使用 PowerShell 脚本 cmdlet 的其他功能,例如参数属性、参数集等...,请选择第二个.

If you want to use the additional features of PowerShell script cmdlets like the parameter attributes, parameter sets etc... then go with the second one.

这篇关于在 Powershell 函数中处理管道和参数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆