Advanced Functions have been around for quite a while now and they still aren’t being used ubiquitously. It isn’t just a more complicated function, it is a defined thing. When you use out of the box cmdlets, they come with many common parameters, like Verbose. This is one of the things that Advanced Functions provide, in addition to the workflow of the function, providing Begin, Process, and End blocks.
How do we create an Advanced Function? Very easily:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-CmdletbindingExample { | |
[CmdletBinding()] | |
Param ( | |
[String[]]$Name | |
) | |
Begin {# Runs once} | |
Process {# Runs for each instance of $Name} | |
End {# Runs once} | |
} |
So, we just plug in CmdletBinding and we’re off to the races. There is certainly a lot available with Advanced Functions. I would argue that the most powerful component is the Begin, Process, and End blocks. The most easily used thing that is available and will likely be useful every day? Verbose.
So, you get the ability to use use the parameters that are commonly out there. One common way to debug our code is to “echo” out different values that you would likely comment out or delete when you work through the issues. With the Verbose parameter, you can now use the Write-Verbose cmdlet; whenever you use the Verbose parameter, then any instance of Write-Verbose will run and only then.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-CmdletbindingExample { | |
[CmdletBinding()] | |
Param ( | |
[String[]]$Name | |
) | |
Begin {# Runs once} | |
Process { | |
# Runs for each instance of $Name | |
Write-Verbose $Name | |
} | |
End {# Runs once} | |
} |
https://gist.github.com/dustindortch/
So, now you can provide some useful options for users of the function, maybe they want some better insights. You also have a debugging option available to you.
EDIT: I would also add that there is a growing movement to use the verbose output as a replacement for inline comments. Instead of writing some comments (and likely never updating them), use Write-Verbose to output something meaningful; it then also stands as comments when you are reading your code. When it is available for output and debugging, the chances up appropriately updating the output are also increased.