powershell blank function

I want to create a function. In powershell. Easy:

 function NAME { }#end function

What name should i use? As a hint, try get-verb name to get a list of ‘approved’ verbs similar to name. Otherwise, use get-name or set-name or suchlike. If i want to use the function alot, i can

set-alias -name shortname -value get-name

so i don’t have to type so much. If i really, really want the alias, i need to save it in a module and load the module in my profile, or set the alias in the profile. the profile is loaded each time i start powershell or i can reload the profile with

.$profile.

The function should have a param scriptblock in case i need to pass a parameter. I might not use it, but as part of a generic shell, it would be useful

Param ([string]$param1)

If i call the function with -param1 thisValue, $param1 will have the value “thisValue” and be of type string. I can make it mandatory and if i don’t provide a value, Powershell will prompt me for it. I can provide a default value, and i can specify the position, so that i don’t need to use the -param convention.

Param (
[Parameter(Position=0,mandatory=$true)]
[string]$param1)
[Paramter (mandatory = $false]
[string]$param2 = "dfault value"
...
)

if you don’t want to use a named parameter but want to pass data to the funciton, you can append values and they will be stored in the $args variable. There is a possible problem if you also have named params. So don’t.

Another parameter variable i find potentially useful is the switch parameter variable. add it to the parameter block as [switch]$name and use it in code as if ($name){ “do something different because of the switch”} when you evoke get-name -switch

param([string]$param1,
[switch]$name
)

The other thing to add to the generic function is put on the first non-commented line in the function:

 [cmdletbinding()]

typically followed with the param block. There are a number of things this function withint a function will do, however enough that you can evoke verbose writes by call the function with the -verbose switch

get-name -verbose

This will cause any statements of the type Write-Verbose “verbose stream” to be sent to the output window, but not without the switch. It makes debugging very easy as well as documentation with just the adding of one parameter variable.  A good thing.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.