DEV Community

taijidude
taijidude

Posted on

1

My first basic powershell module

Hello everyone, I'm back after a nearly two week pause. Had some back pain problems and wanted to avoid sitting in front of the computer so much. But now I'm better and eager to code and write again. So let's go.

During the last year I started to use powershell to automate some application deployments on multiple projects. Found some parts where the code is really similar, so i want to extract those parts into a module.

The build scripts are going to be used on various machines from various colleagues. So I wanted a solution with as little setup as possible.

My example module consists of two files:

Alt Text

m1.psm1: Contains the code for the module

function testName($toTest) {
    "Validating: $toTest"
    if($toTest -eq "test") {
        throw "The value of the parameter to test is incorrect!"
    }
}

function helloWorld() {
    "This is a hello world from a module!"
}

Export-ModuleMember -Function "helloWorld"
Export-ModuleMember -Function "testName"

Enter fullscreen mode Exit fullscreen mode

Notice the two Export Statements at the bottom. Exporting your module functions makes them usable outside of the module.

m1.psd1: This file is the module manifest and contains metadata about the module. It is created via the New-ModuleManifest Commandlet. I don't know much about it but pointing the property RootModule to my script file in the module helped to get rid of some errors where functions where not recognized.

RootModule = './m1.psm1'
Enter fullscreen mode Exit fullscreen mode

also see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/new-modulemanifest?view=powershell-7.1

Finally the code to test it all:

Import-Module .\m1\m1.psm1
helloWorld
testName -toTest "test"
Enter fullscreen mode Exit fullscreen mode

Alt Text

Notice here that I use the relative path to import the Module. Please remember that i'm using this for deployment scripts which might be run by my colleagues on their machines. I want to avoid them having to install and update the module when something changes. I will just commit the deployment script and module with the project in git and expect that it should work with having to install anything.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay