FUNctions: Episode I, The Phantom Module

Functions intimidated me for the longest time. I just couldn’t wrap my head around them, but now I’m a “functioneer”. If I wasn’t so busy lazy, I’d write most of scripts into functions.

Section 1 | What the F….un is a Function?

“What is a function?” you ask. Its a reusable block of code that you can repeatedly reference in your script or program. Insanity is using the same block of code over-and-over again, but with functions, you can simply write it once, and reuse it throughout your project or day to day use.

Basic example in PowerShell:

function Verb-Noun {
    Param
    (
        $Parameter1,
        $Parameter2
    )
}

So for a real world example. We could do something like this:

function Write-Blog {
    Param
    (
        $Content,
        $Images
    )
}

Then you’d call it in your script like so:

Write-Blog -Content "a couple paragraphs of junk" -Images "link to .jpg"

That’s the gist of it. I don’t want to overcomplicate things with bits like CmdletBinding and more advanced options.

Section 2 | Your Very Own PowerShell Module

You too can make your own file containing all of your functions. All you need to do is:

  1. In PowerShell, run $env:PSModulePath to find where your modules are stored.
  2. Navigate to that path and create a folder named whatever you want. We’ll call it “MyFunctions” for this example.
  3. Within your MyFunctions folder, create MyFunctions.psm1.
  4. Populate MyFunctions.psm1 with your functions

Now you can call your custom functions from the shell at any time.