Creating Custom Powershell libraries
Powershell is a very powerful tool for automating tasks. Creating your own nuget repository that hosts powershell modules is a great way to distrubute powershell scripts, but it can be a bit fiddly to setup.
When creating your own modules, it can be quite fiddly to actually get them setup on a central repository. Nuget repos natively support powershell modules so its actually quite straight forward once they are setup. Its just a case of knowing the right sequence of commands to get setup and connected to the repository source.
New-ModuleManifest -Path '<path-to-manifest>.psd1'
-RootModule '<module-name>.psm1' -Author 'me'
Here's an example for our Greetings.psm1
Once run, you should see the new psd1 file in the output directory:
import-module Greetings
When creating your own modules, it can be quite fiddly to actually get them setup on a central repository. Nuget repos natively support powershell modules so its actually quite straight forward once they are setup. Its just a case of knowing the right sequence of commands to get setup and connected to the repository source.
The basic steps are:
- Create a powershell script
- Save as a .psm1 file in one of the module path directories
- Create a Module Manifest
- Load the module into the current session
- Push the module to a remote nuget repository
Creating a basic Script
The first couple of steps are as simple as they sound. Create a simple function and save it as a powershell script. For example:
Run the following command to see where the environment module paths are:
$env:PSModulePath.Split(';')
On my system this meant that the following directory was a module path:
C:\Program Files\WindowsPowerShell\Modules
Once the psm1 file is saved to this directory, you can see it in your powershell session by running:
Get-Module -ListAvailable
Creating a Module Manifest
You will notice in the above screenshot that the version is set to 0.0. In order to set this and other metadata you can create a module manifest. The module manifest is an array of data in a seperate psd1 file with the same name as the module. You can create one using the following cmdlet:New-ModuleManifest -Path '<path-to-manifest>.psd1'
-RootModule '<module-name>.psm1' -Author 'me'
Here's an example for our Greetings.psm1
Once run, you should see the new psd1 file in the output directory:
Loading the Module
We have now created our module and it is on our local system and if we re-run Get-Module we should see it, now with the version number set. We can import that module into the session and start calling the methods on it like any other module.import-module Greetings