How to implement powershell function library?

I recently worked on a project that we had to deploy using powershell scripts. We encoded 2,000 lines, more or less, in different files. Some of them were devoted to generally accepted methods, but after coding 500 lines for each of them, it was difficult to find which method to use, or if it was necessary to implement a new one.

So my question is about the best way to implement powershell function library:

Better to have some files with more code than to have many files with multiple lines of code?

+4
source share
4 answers

You can create a Module where you can save all your scripts intended for ordinary tasks.

+3
source

The answer from @MikeShepard conceptually is the way to go. Here are just a few implementation ideas to help you:

  • I have open source libraries in several languages. My PowerShell API starts with the top level organized into different topics, as suggested by Mike Shepard.

  • For these topics (modules) with more than one function (for example, SvnSupport), each public function is in a separate file with its private support functions and variables, thereby increasing linkage and reducing communication.

  • To combine a collection of functions in a topic (module) together, you can list them individually (either by counting points or in a manifest, as @ Thomas Lee suggested). But I prefer the technique that I took from Scott Mook. Use the following code as the entire contents of your .psm1 file and put each of your other functions in separate .ps1 files in the same directory.


Resolve-Path $PSScriptRoot\*.ps1 | ? { -not ($_.ProviderPath.Contains(".Tests.")) } | % { . $_.ProviderPath } 

In fact, much more can be said about functions and modules; an interested reader can find my article Further down the Rabbit Hole: PowerShell modules and encapsulation , published on Simple-Talk.com, are a useful starting point.

+5
source

I agree with @Christian's suggestion and use the module.

One tatich that you can use is to break the module into several scenarios and include them in the last module. You can either show that they are point sources in the .PSM1 file, or specify the files in the manifest (.PSD1 file).

0
source

I tend to have several subject-based modules (fluent, nouns). For example, if I had a bunch of functions related to MongoDB, I would have a MongoDB module. This makes it easy to draw them into the session if I need them, but it does not interfere with each session with a bunch of functions that I rarely use. A consistent naming convention makes it easy to know what to import. For example, modMongoDB.psm1 will be easy to remember.

As an additional note in the module loading module 3.0, you can configure automatic mode, so there is no need to preload a bunch of modules in your profile.

0
source

All Articles