it:ad:powershell:howto:create_a_function

IT:AD:PowerShell:HowTo:Create a Function

Summary

  • Use the function keyword
  • Enclose in brackets
  • Define them earlier than invoked (ie, put them at the top of you .ps1 files). Can pass args two ways:
    • Define either name args (but have to invoke them with name args), or
      • Name args can have default values.
      • use $args\[0\] to get to the passed arguments.

Example:

    #define:
    function MyFunction ($dir, $minSize=1000) {
      return $null;
    }
    #then invoke:
    MyFunction -dir "..." -minSize 10000
<sxh>

or just use args:


<sxh powershell>
    #define:
    function MyFunction  {
      return $null;
    }
    #then invoke:
    MyFunction "..." 10000

A key concept of Powershell is that even if you define an array return variable, if the array only contains one item, it will unravel it to only one item.

Annoying no end chasing that down.

A way to force it to stay as an array is to wrap it in @(…) before handing it back:

function MyFunc(){


    [System.Collections.ArrayList]$private:results = New-Object System.Collections.ArrayList;

    foreach ($entry in Get-ChildItem $directoryFullName -filter $filter -Recurse){
        $results += $entry.FullName;
    }     
    return ,$results;
}

That said, the good news is you don't have to do anything similar for hashtables – they just work:



function ABC () {
    $results = @{};

    #$results["A"] = "B";
    #$results["B"] = "C";

    return $results;
}

$a = ABC;
$a.getType();


IsPublic IsSerial Name                                     BaseType                                                                                                                                    
-------- -------- ----                                     --------                                                                                                                                    
True     True     Hashtable                                System.Object                                                                                                                               


  • /home/skysigal/public_html/data/pages/it/ad/powershell/howto/create_a_function.txt
  • Last modified: 2023/11/04 23:01
  • by 127.0.0.1