DEV Community

taijidude
taijidude

Posted on

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.

Discussion (0)