Functions


Search pages under this topic

I welcome feedback on these articles.  Feel free to add comments in the article's comment section.  If you found an article useful, hit the Like button to know the article was useful


Intro

Notes on defining and using functions in Powershell, including how to pass arguments and return values.



Documentation




Function Parameters


Parameter Block


This is how you define a parameter block that specifies how the arguments are to be treated.


Don't forget the open brace after the function name or you will spend a lot of time debugging strange problems


function Initialize
{
    param(
        [string][Parameter(Mandatory=$true)]$stringArg,
        [bool][Parameter(Mandatory=$true)]$enabled=$false
    )


You can also do it this way but the above way is preferred because you can qualify the parameters

function Initialize($stringArg, $enabled) 
{


Mandatory

The Mandatory parameter attribute flag set to $true indicates that the caller to this function MUST specify this parameter.

[Parameter(Mandatory=$true)]


To detect the caller provided a parameter or the function's default was used, try this:


if(-not($PSBoundParameters.ContainsKey('EmailTo')) -and $EmailTo)
{
    # User relied on default value
}

Source: Mandatory and default parameters of a function



Parameter As An Option


What if you want to pass a parameter like a boolean option (-enabled), use this approach.


param (
    [switch]$enabled
);

if ($enabled) {
    Write-Host "is enabled."
}
else {
    Write-Host "is not enabled."
}




Returning Values


This is really important to remember.  In Powershell, any output generated by a function is returned to its caller!  See documentation: about_Return.  


In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword.


What this means is that calling function may some unexpected data if your function doesn't handle it well. To avoid this, I make sure all statements store their output in a variable or I pipe the statements to | Out-Null


If you need to return an array or any other collection, keep this in mind.


When you return a collection from your script block or function, PowerShell automatically unrolls the members and passes them one at a time through the pipeline.


This means you can't simply return an array variable like

return $a


You must specify it is an array (put a comma in front of the variable name)

return ,$a



Testing Command Success


If you want to test the success of a command use "$?"


    if (Test-Path $library) 
    {
    	$added = Add-Type -Path $library
        if ($?)
        {
            $libraryFound= $true
        }
    }




How To Invoke A Method From A C# Library


See How To: Invoke A Method From A C# Library