PowerShell scripts are a popular choice for task automation because they are simple, human-readable, and easy to master.
In this article, we will talk about PowerShell modules and their installation, but a touch on the basics.
What is PowerShell?
PowerShell is an automation and configuration management platform from Microsoft that eases the process of building, testing and deploying solutions in a CI/CD environment. Built on the .NET Common Language Runtime (CLR), this platform consists of a command-line shell, associated scripting language, and automation and configuration management framework.
Why Use PowerShell Scripting?
Here are some reasons for the huge popularity of PowerShell scripting.
- Inputs and outputs are .NET objects, so it is a natural choice for .NET developers.
- Requires no additional parsing to extract data from the output, as you can modify the script to provide the information you need.
- Highly extensible through functions, scripts, and modules.
- Comes with a simple formatting system for easy readability.
- Enables you to create dynamic data types.
- Provides built-in support for data formats like CSV, JSON, and XML.
Now that you know what PowerShell is and the reasons for its popularity, let's move on to a specific component called PowerShell modules.
What are PowerShell Modules?
PowerShell modules are nothing but a combination of scripts that perform a similar function.
Let's understand this with an example.
You're an expert in PowerShell scripting, and you create scripts for different problems. However, they are likely to be stored across your devices, servers, coworkers' devices, etc.
In other words, the scripts are all over the place, and you have no idea which script is located where. This becomes a problem when you want to reuse scripts. Also, it becomes a problem when you begin to create comprehensive solutions that can be used organization-wide.
A streamlined option to this situation is PowerShell modules as they combine similar scripts or those geared towards solving different aspects of the same problem into a cohesive unit, so you have better control over its storage and usage, which makes it easy to share your code with others, reuse when needed, and provides a structure to the code.
Overall, a PowerShell module can contain,
- One or more PowerShell scripts.
- Additional assemblies and files that the scripts may need.
- A Manifest file stores the metadata such as description, author, and versions of the above files.
- A directory containing the above files is in a location that PowerShell can access.
Note that all these files are not mandatory for a module. For example, a module can contain just a manifest file or a script dynamically creating manifest files and directories.
Types of PowerShell Modules
There are four types of PowerShell modules, and they are:
- Script Modules – A script module is a file with a psm1 extension and contains any valid PowerShell code. This is not a dynamic module, so it must be created and saved in a folder accessible by PowerShell.
- Binary Modules – A .NET framework assembly file with a DLL extension and contains compiled code. These modules enable you to create custom cmdlets for hard-to-code functionality such as multithreading.
- Manifest Modules – This module contains only the manifest file and no other code or assembly.
- Dynamic Modules – These modules are created dynamically with a script and are often used for creating modules on-demand.
Now that we have a grasp of the basics let's dive into its technical implementation.
Installing PowerShell Modules
There are many ways to install a PowerShell module, so let's look at each of these methods in detail.
Install from a PowerShell Gallery
The easiest way is to install a module from the PowerShell gallery.
This gallery is a central repository of PowerShell scripts online, and by default, it contains Microsoft-authored modules.
Click here to go to the PowerShell Gallery, where you can search for specific modules.
Once you identify the module, download it to your device. Next, open PowerShell and type this code.
install-module -Name PackageManagement
Here, PackageManagement is the name of the module you want to install.
Depending on the module's code, you may get a pop-up asking you to confirm the installation. Click Yes, and the structure will happen automatically.
Once the installation is completed, check with the following command.
Get-Module -ListAvailable
Look through this list and check if your module is in it.
If it is present, start exploring the module. Look for the commands it contains with the code,
Get-Command -module PackageManagement
Accordingly, start using it.
On the other hand, if your module is not present, check your Execution Policy to prevent the modules from getting installed. Often, a highly restrictive policy is used by organizations as a part of their security measures.
Check your execution policy with the following command.
Get-ExecutionPolicy -List
You can change the policy with the following command depending on what you see.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine
Do a Manual Install
The above method works only if you want to use a pre-existing module available in the PowerShell Gallery.
For custom modules that you've created or to install the ones that are not available in the PowerShell Gallery, go for a manual install.
Here is a step-by-step guide on how you can do it.
Check the PSModulePath
PSModulePath is an environment variable that contains the absolute file path for modules. PowerShell will look for modules mentioned in this environment variable's way, so make sure you have your module copied to this path.
To see the value of PSModulePath, type
$Env:PSModulePath
This can return many paths. However, you must specifically look for this path: C:\program files\WindowsPowerShell\Modules\<Module FOlder>\<Module Name> to make a module accessible for all users.
Note that the module folder and module name must be identical.
If you want only specific users to access your module, use this path: C:\Users\userprofile\Documents\WindowsPowerShell\modules
Though you can add a new path to the environment variable, it's best to stick to the above two URLs for easy management in the future.
Move your Module
Once you know the path, copy your module to that folder.
That's it. This is the manual way of installing the module.
To check, run the command
Get-Module -ListAvailable
And you should see your module.
Import the Module
The third way to install PowerShell modules is to import existing ones into active memory so that you can access the same in the current session.
Use the following command to import the modules.
Import-module -name ModuleName
Most times, this is not an independent way of installing a PowerShell module. Instead, you can import the existing modules to active memory for quick access.
Thus, these are some ways to install a PowerShell module.
Before we end, let's look at some best practices for designing and installing PowerShell modules.
Best practices for Module Design and Installation
Here are some best practices for designing modules and installing them, so your users can get the most out of them.
Explore the Functionality
Before you start using the module, explore its functionality. An excellent way to do this is to use the command, Get-Module -ListAvailable
Once you look at the functionality, it can get more manageable for you to use the module well.
If you're the developer of a module, provide explicit information about each function in the manifest file to help your users understand your work better.
Create the Manifest File
The easiest way to create the manifest file is through the New-ModuleManifest cmdlet.
Its syntax is,
New-ModuleManifest [-Path] <string> -Author <string> -CompanyName <string> -Copyright <string> -Description <string> -FileList <string[]> -FormatsToProcess <string[]> -ModuleToProcess <string> -NestedModules <string[]> -RequiredAssemblies <string[]> -TypesToProcess <string[]> [-AliasesToExport <string[]>] [-ClrVersion <Version>] [-CmdletsToExport <string[]>] [-DotNetFrameworkVersion <Version>] [-FunctionsToExport <string[]>] [-Guid <Guid>] [-ModuleList <Object[]>] [-ModuleVersion <Version>] [-PassThru] [-PowerShellHostName <string>] [-PowerShellHostVersion <Version>] [-PowerShellVersion <Version>] [-PrivateData <Object>] [-ProcessorArchitecture {<None> | <MSIL> | <X86> | <IA64> | <Amd64>}] [-RequiredModules <Object[]>] [-ScriptsToProcess <string[]>] [-VariablesToExport <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>]
When you populate these fields with the corresponding values, a manifest file is automatically created and saved in the given path.
Naming Conventions
While PowerShell doesn't insist too much on naming conventions, it is an excellent practice to follow the standard ways, so your functions are self-explanatory. More importantly, it can help with maintenance and extensibility as needed.
Name Collisions
It is a good programming practice to avoid name collisions. Make sure that your functions don't have the same names as those of cmdlets.
But what if there is an accidental collision? How does PowerShell pick the right one?
PowerShell has a clear order of precedence – Alias, Function, Cmdlet, and Native Windows commands.
Be aware of this order to make the right naming decisions.
Focus on Documentation
We tend to focus on the programming itself and not on the documentation.
Good programming practice involves having thorough documentation of the function and inline comments to help users of all technical knowledge make sense of your code.
You can add comments in the module script file as you write the program. Many IDEs provide good support for adding these comments so that you can leverage them.
In all, the above practices can make your code more readable and easier to maintain. While this is not an exhaustive list, it is sure to get you started in the right direction.
Conclusion
To conclude, PowerShell modules are a handy way to keep all your similar scripts together, so you can use them quickly when needed.
There are two broad ways to install the modules, manually and directly from the PowerShell Gallery. We hope the detailed steps will help to establish your modules quickly.
PowerShell Modules Installation FAQs
What is a PowerShell module?
A PowerShell module is a package of related functions, cmdlets, and scripts that can be used to extend the functionality of PowerShell.
What are some common PowerShell modules?
Common PowerShell modules include Active Directory, Exchange, and SharePoint.
What are some common issues that can arise when using PowerShell modules?
Some common issues that can arise when using PowerShell modules include version conflicts, module dependencies, and compatibility issues with existing infrastructure.
What are some best practices for creating and maintaining PowerShell modules?
Best practices for creating and maintaining PowerShell modules include following a consistent naming convention, documenting module functionality and dependencies, and testing and verifying module functionality before release.
What are some common use cases for custom PowerShell modules?
Common use cases for custom PowerShell modules include automating repetitive tasks, configuring and managing network devices, and integrating with external systems and applications.