Combine Powershell Scripts into a module

A.R. picture A.R. · May 16, 2013 · Viewed 11.4k times · Source

I have a half dozen powershell scripts (.ps1 files) that all have related functionality. Is there an easy way that I can combine them into a module so that I can call them like they were normal CmdLets ?

For example, insteading of running:

PS> ./get-somedata.ps1 -myParams x

I could import the module and write:

PS> get-somedata -myParams x

Answer

Frode F. picture Frode F. · May 16, 2013

You should create a script module. First, turn your scripts into functions(so you can skip the .\ when calling them). This is as easy as wrapping the script content in a function scriptblock. Ex.

get-somedata.ps1

$data = get-childitem -filter *.doc
$data | ft -autosize

is turned into.

get-somedata.ps1

function get-somedata {
    $data = get-childitem -filter *.doc
    $data | ft -autosize
}

Then you can either create a *.psm1 file that contains all your new functions, or a *.psm1 file that runs the seperate scripts (since they are now wrapped inside function scripblocks, the functions will be imported instead of being run when you run the script files). If you want more control over name, filelist, version etc. you can create a module manifest. The link above explains some of it.

Check out this link.