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

编程入门 行业动态 更新时间:2024-10-28 01:25:45
本文介绍了在 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 函数中处理管道和参数输入

本文发布于:2023-07-08 05:21:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1072497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   管道   参数   Powershell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!