Home Powershell Modules and Functions
Post
Cancel

Powershell Modules and Functions

Here we’re going to talk about Powershell Modules and Functions.

A Function is a section of code that you can call over and over again. You can give it parameters and the code will run using those variables.

Here is a template for a simple function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Example-Function-Name {
    param (
        [Parameter(
            Mandatory = $true, # this makes the variable to pass in mandatory if you don't add one then the function will fail.
            Position = 0
        )] $variable # the variable that you pass into the function
    )

# Here is where you insert your code blocks
write-host "This is the variable $variable"

# if the variable were a number then you could action some math and return it to the main code logic 

$newvariable = $variable += 1 #This takes the $variable and adds 1, then saves it as a new variable called $newvariable

return $newvariable # this returns the new variable back to the main to the main code logic
}

To call the function in the main code logic you can do the following.

1
2

$thereturnvalue = Example-Function-Name $variable #You can call the $variable what ever you like in the main code.

Modules

Modules are quite simple. They are a basically functions like the above in separate files and are imported into the main code.

You can call them in the main code by creating a Modules.psm1 file. This is what it looks like inside the Modules.psm1

Before you do that you that you need to save the function in a separate file. Lets use the name of the function as the file name.

1
Example-Function-Name.ps1

Now create another file called Modules.psm1 and add this

1
. $PSScriptRoot\Example-Function-Name.ps1

Now in the main code you can call the functions by the following

1
import-module .\Modules.psm1 -Force

From there you can call the function that you made just like you did if the function was in the main code. It can clean up your scripts and make it easier to modify when you have a big program you’re working on

This post is licensed under CC BY 4.0 by the author.
Trending Tags