Function design

In order to always support all common parameters, it is recommended to include a CmdletBinding attribute in your cmdlet, even if you do not want to use any parameters. This gives the executing user full control over error handling and output. Additionally, always use the proper verbs to express what your function does. Get-Verb shows plenty of approved verbs that will make your cmdlet easier to find:

Using the CmdletBinding attribute is very easy and provides many benefits. There is no reason to not go the proverbial extra mile in the form of a couple of keystrokes, as seen in the following code sample:

# CmdletBinding to allow common parameters
function Get-ContosoVm
{
[CmdletBinding()]
param ( )

'does something'
}

If your function uses parameters, always add the type to them, as well as a parameter attribute and possible validation attributes, to them. If a parameter is mandatory, consider adding a help message, as well, in case a user forgets a mandatory parameter and does not know what they should enter.

Add parameter comments close to the actual parameter, rather than adding them to the inline help, to make the comment more visible in your code, as the next code sample illustrates:

function Remove-ContosoVm
{
[CmdletBinding()]
param
(
# A comma-separated list of VM names to deprovision
[Parameter(
Mandatory,
HelpMessage = 'Please enter a comma-separated list of VM names'
)]
[string[]]
$ComputerName,

# An optional timeout in minutes for this operation
[Parameter()]
[int]
$TimeoutInMinutes = 5
)
}

# Cmdlet syntax is properly displayed
Get-Command -Syntax -Name Remove-ContosoVm

# Help is populated properly
Get-Help -Name Remove-ContosoVm -Parameter TimeoutInMinutes
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset