Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

powershell - What is [cmdletbinding()] and how does it work?

According to get-help about_Functions_CmdletBindingAttribute

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

We can use it on the top of our scripts. What is the function in this case? An internal implicit "main" function called by the PowerShell engine for all its inputs?

Regarding this syntax:

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

What are we doing? Instantiating a cmdlbinding object and passing an argument list to its constructor? This syntax can be found in param() - for example: [Parameter(ValueFromPipeline=$true)]. Does this syntax have a particular name, and can it be found elsewhere?

Lastly, are we able, as simple PowerShellers, to mimic this functionality and modify the behavior of scripts by setting an attribute?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CmdletBinding, Parameter etc. are special attribute classes that scripters can use to define PowerShell's behavior, e.g. make a function an Advanced function with Cmdlet capabilites.

When you call them via e.g. [CmdletBinding()] you initialize a new instance of the class.

Read more about the CmdletBindingAttribute class at: MSDN

Read more about the ParameterAttribute class at: MSDN

More about Attribute classes here and here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...