Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a powershell functions library?

I recently worked on a project that we had to deployed using powershell scripts. We coded 2000 of lines, more or less, in different files. Some of them were dedicated to common methods but, after coding 500 lines for each one, it was hard to find what method to use or if it was necessary to implement a new one.

So, my question regards to what is the best way to implement a powershell functions library:

Is better having some files with lot of code than having a lot of files with few lines of code?

like image 222
jaloplo Avatar asked Jul 19 '12 08:07

jaloplo


People also ask

How do you create a function in PowerShell?

A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.

How do you store functions in PowerShell?

You can also save your function in a PowerShell script file. Type your function in a text file, and then save the file with the . ps1 filename extension.


2 Answers

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

  • I have open-source libraries in a number of languages. My PowerShell API starts with the top-level being organized into different topics, as Mike Shepard suggested.

  • For those topics (modules) with more than one function (e.g. SvnSupport), each public function is in a separate file with its private support functions and variables, thereby increasing cohesion and decreasing coupling.

  • To wrap the collection of functions within a topic (module) together, you could enumerate them individually (either by dot-sourcing or including in the manifest, as @Thomas Lee suggested). But my preference is for a technique I picked up from Scott Muc. Use the following code as the entire contents of your .psm1 file and place each of your other functions in separate .ps1 files in the same directory.


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

There is actually quite a lot more to say about functions and modules; the interested reader might find my article Further Down the Rabbit Hole: PowerShell Modules and Encapsulation published on Simple-Talk.com a useful starting point.

like image 143
Michael Sorens Avatar answered Nov 15 '22 05:11

Michael Sorens


You can create a Module where you can store all your script dedicated to common jobs.

like image 39
CB. Avatar answered Nov 15 '22 03:11

CB.