powershell - 什么是 [cmdletbinding()] 以及它如何工作?

标签 powershell binding arguments parameter-passing powershell-cmdlet

根据get-help about_Functions_CmdletBindingAttribute

The CmdletBinding attribute is an attribute of functions that makes them operate like compiled cmdlets

我们可以在脚本顶部使用它。在这种情况下,它的作用是什么? PowerShell 引擎为其所有输入调用的内部隐式“main”函数?

关于此语法:

[CmdletBinding(ConfirmImpact=<String>,
                     DefaultParameterSetName=<String>,
                     HelpURI=<URI>,
                     SupportsPaging=<Boolean>,
                     SupportsShouldProcess=<Boolean>,
                     PositionalBinding=<Boolean>)]

我们在做什么?实例化 cmdlbinding 对象并将参数列表传递给其构造函数?此语法可以在 param() 中找到 - 例如:[Parameter(ValueFromPipeline=$true)]。这个语法有特定的名称吗?可以在其他地方找到吗?

最后,我们是否能够作为简单的 PowerShellers 来模仿此功能并通过设置属性来修改脚本的行为?

最佳答案

一般来说,CmdletBinding 使函数成为高级函数。将它放在脚本的顶部使该脚本成为“高级”脚本。函数和脚本非常相似,其中脚本文件名相当于函数名称,脚本内容相当于函数的脚本 block 部分。

CmdletBinding 属性使您可以控制函数功能,例如添加Confirm 和WhatIf 支持(通过SupportsShouldProcess)、禁用参数位置绑定(bind)等。

关于powershell - 什么是 [cmdletbinding()] 以及它如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14671051/

相关文章:

regex - PowerShell 从脚本中删除所有注释

绑定(bind)路径中的 WPF 强制转换

wpf - 绑定(bind)驱动的索引属性不返回

c++ - 我可以在 1 行中使用非默认数据类型作为函数的参数吗?

arrays - 将数组作为单独的参数传递给 PowerShell 脚本

powershell - 带排除的移动项目不起作用

regex - 在 Powershell 中使用正则表达式匹配 $$

android - 为什么 Service 在 Activity 被销毁时会 self 销毁?

python - 当我在Python中运行文件时出现ValueError

arrays - 与 AD 中的职位列表匹配的用户列表