Categories

Creating a module

I’m writing a new PowerShell book and have got to the fun bit where I’m creating lots of scripts. I wanted to supply these as a series of modules. So each individual listing is a function. But I don’t want to manually maintain the module file as I’m working through each chapter. Usually I create a module with one .psm1 file that has all of the functions in it.

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015

## get folder name
$path = Get-Location
$folder = Split-Path -Path $path.path -Leaf

$mfile =  "$folder.psm1"

## remove old module file
if (Test-Path -Path $mfile){Remove-Item -Path $mfile}
 
## get files
Get-ChildItem -Filter *.ps1 | 
Select Name | Sort Name |
foreach {
 ". ./$($_.Name)" | Out-File -FilePath $mfile -Append
}

 

It is also possible to have a .psm1 file that runs a set of other PowerShell scripts. So that’s what I’ve done. The script shows how I can create a module file by getting the names of the individual PowerShell files adding the “. ./” in front to dot source them.

One quick module file with minimum effort.

Leave a Reply