Powershell: basic functions
Powershell PowershellAll good PowerShell revolves around functions, and in a nutshell they’re reusable snippets of code that you’ll call upon multiple times during the running of any script.
You can group functions into powershell modules .psm1, and these can then be imported into any script you wish.
The script below is the foundations of how a function operates, and I’ll try to break it down into understandable sections.
Section 1. Your function should tell someone using it, what it does, how to use it with commented examples, and you should try and incorporate inbuilt cmdlet bindings like -verbose, -whatif etc.
Section 2.
The function itself, try to follow best practices and naming conventions (get-, set-, new-, remove-) this can stop confusions when others are using your functions, then a logical name for the function, so in the example get-somthingelse
Section 3.
Parameters, these are the bread and butter of a function, they can be mandatory or not, but best to keep you functions users on the path, the script below has mandatory and non mandatory parameters, the $computername is mandatory if you don’t enter it, it’ll not run the function.
Section 4.
The Workhorse part of the function, this is where it uses those parameters to carry out your action.
Then at the bottom, I’ve included an example, but your function can be as complex as you require it to be (or as simple as a one liner).
#author: Richard Easton
#description: Function Template with Mandatory parameters
#usage: get-somethingelse -somethingelse1 "Hello World!" -Computename $env:ComputerName -verbose
# Wrapping the workhorse part of the function in the $PSCmdlet.ShouldProcess if statement
# gives you access to -Whatif -Verbose -Debug etc etc (Common functions).
#
# Try removing the -Computername $env:computername to see what happens ;)
function get-somethingelse {
[cmdletbinding(SupportsShouldProcess)]
param (
# add parameter that is mandatory [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()]
[string]$somethingelse1,
# add parameters for computername (mandatory) and credentials:
[Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string[]] $ComputerName, [PSCredential] $somethingelse2 ) if ($PSCmdlet.ShouldProcess($computername, $workspaceId
)
) {
write-host "$somethingelse1: from $ComputerName"
}
}
#example get-somethingelse -somethingelse1 "hello world" -ComputerName $env:COMPUTERNAME -verbose | Out-Null
Enjoy and happy POSH scripting.