A.R.
A.R.

Reputation: 15685

Combine Powershell Scripts into a module

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

Upvotes: 3

Views: 12662

Answers (3)

user2850560
user2850560

Reputation: 101

Well I wanted to do the same thing and did not want to have to create one massive module file. (as I edit my files somewhat often)

So this is what I did. Ugly but works great! Done is seconds.

$Module = c:\users\<username>\documents\windowspowershell\module\mycustommodule\mycustommodule.psm1
#Added so when I make changes to scripts I can easily rebuild the module file.
Clear-content $module

$Scripts = c:\<scriptfolder>
$FileList = gci $Scripts

foreach ($File in $FIleList) 
{   $name = $File.basename
    $OpenFunction = "`n`n`n`n Function $Name { `n"
    $CloseFunction = "`n}"
    add-content $openfunction -path $module    
    $File | get-content | add-content -path $module
    add-content $closefunction -path $module
}

Now you can import-module mycustommodule

and call one of your functions which have the same names as your original scripts. :-)

Upvotes: 1

Lars Truijens
Lars Truijens

Reputation: 43602

There are several options.

Put your script in the a folder from $env:Path or add your script folder to $env:Path. You also don't need to specify .ps1

Turn your scripts into functions and add them to your profile script ($profile). This script runs when powershell starts. You can also dot source your scripts with your functions in the profile.

Turn your scripts into functions and add them to a module. Don't forget to import your module before using. You can do that in your powershell profile so it's done every time you start powershell. Or use powershell v3 which can auto load modules. Then make sure your module is in one of the folders of $PSModulePath.

Upvotes: 1

Frode F.
Frode F.

Reputation: 54821

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.

Upvotes: 2

Related Questions