Menu

Using Powershell Modules

PowerShellGet and PackageManagement

First we are going to cover the two fundamental modules that run most module/package stuff in powershell. PackageManagement and PowerShellGet work hand in hand with each other. When you run Install-module for PackageManagement you will generally get a failure because you are currently using PackageManagement because PowerShellGet is using it to run Install-Module (meta… I know). There are dozens of tutorials that explain this in more detail so I won’t get in to the specifics, just recommend the following command:

powershell.exe -NoLogo -NoProfile -Command '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope AllUsers -AllowClobber -Repository PSGallery'

This will run the install command in a new session and should upgrade your PackageManagement.

What just happened?

The script above is actually doing something quite simple. Windows will store packages in the %programfiles%\WindowsPowerShell directory. This is the GLOBAL location for modules. When you run powershell as an admin, this is where modules go. When you are not running as an admin, it will generally use %userprofile%\Documents\WindowsPowerShell. These settings can be tweaked/overridden using profile scripts. If you navigate to the WindowsPowerShell directory you will find a modules folder, which will have a PackageManagment folder. In that folder you will see the different versions that you have installed. Additionally you can use the following command to see what powershell is loading from $ENV:PSMODULEPATH:

Get-InstalledModule

Module and script construction

I have put together a simple module that uses some simple powershell functions to build templates for scripts and modules. Run the following commands:

install-module xanderu.helpers
New-PowershellTemplate

This will automatically create a module or script based on the input prompts. If you haven’t specified a directory, it will use you current directory to create the structure.

Loading and debugging modules

Without a pipeline, loading and debugging modules is actually quite simple. By copying the module into the %programfiles%\WindowsPowerShell directory it will auto load when you open powershell. This can cause issues when debugging as it can get confusing when you are trying to make changes. You will not be sure what version of the modules functions you are using. Instead, when debugging use:

Import-Module -force -allowclobber .\Path\to\module.psm1

This will allow you to specify exactly what module you want to load. It will automatically override and replace any functions you have in your current session.

Leave a Reply

Your email address will not be published. Required fields are marked *