Перейти к содержимому

Как установить модуль в powershell

  • автор:

Name already in use

PowerShell-Docs / reference / docs-conceptual / developer / module / installing-a-powershell-module.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Installing a PowerShell Module

After you have created your PowerShell module, you will likely want to install the module on a system, so that you or others may use it. Generally speaking, this consists of copying the module files (ie, the .psm1, or the binary assembly, the module manifest, and any other associated files) onto a directory on that computer. For a very small project, this may be as simple as copying and pasting the files with Windows Explorer onto a single remote computer; however, for larger solutions you may wish to use a more sophisticated installation process. Regardless of how you get your module onto the system, PowerShell can use a number of techniques that will let users find and use your modules. Therefore, the main issue for installation is ensuring that PowerShell will be able to find your module. For more information, see Importing a PowerShell Module.

Rules for Installing Modules

The following information pertains to all modules, including modules that you create for your own use, modules that you get from other parties, and modules that you distribute to others.

Install Modules in PSModulePath

Whenever possible, install all modules in a path that is listed in the PSModulePath environment variable or add the module path to the PSModulePath environment variable value.

The PSModulePath environment variable ( $Env:PSModulePath ) contains the locations of Windows PowerShell modules. Cmdlets rely on the value of this environment variable to find modules.

By default, the PSModulePath environment variable value contains the following system and user module directories, but you can add to and edit the value.

[!WARNING] This location is reserved for modules that ship with Windows. Do not install modules to this location.

To get the value of the PSModulePath environment variable, use either of the following commands.

To add a module path to value of the PSModulePath environment variable value, use the following command format. This format uses the SetEnvironmentVariable method of the System.Environment class to make a session-independent change to the PSModulePath environment variable.

[!IMPORTANT] Once you have added the path to PSModulePath, you should broadcast an environment message about the change. Broadcasting the change allows other applications, such as the shell, to pick up the change. To broadcast the change, have your product installation code send a WM_SETTINGCHANGE message with lParam set to the string «Environment». Be sure to send the message after your module installation code has updated PSModulePath.

Use the Correct Module Directory Name

A well-formed module is a module that is stored in a directory that has the same name as the base name of at least one file in the module directory. If a module is not well-formed, Windows PowerShell does not recognize it as a module.

The «base name» of a file is the name without the file name extension. In a well-formed module, the name of the directory that contains the module files must match the base name of at least one file in the module.

For example, in the sample Fabrikam module, the directory that contains the module files is named «Fabrikam» and at least one file has the «Fabrikam» base name. In this case, both Fabrikam.psd1 and Fabrikam.dll have the «Fabrikam» base name.

Effect of Incorrect Installation

If the module is not well-formed and its location is not included in the value of the PSModulePath environment variable, basic discovery features of Windows PowerShell, such as the following, do not work.

The Module Auto-Loading feature cannot import the module automatically.

The ListAvailable parameter of the Get-Module cmdlet cannot find the module.

The Import-Module cmdlet cannot find the module. To import the module, you must provide the full path to the root module file or module manifest file.

Additional features, such as the following, do not work unless the module is imported into the session. In well-formed modules in the PSModulePath environment variable, these features work even when the module is not imported into the session.

The Get-Command cmdlet cannot find commands in the module.

The Update-Help and Save-Help cmdlets cannot update or save help for the module.

The Show-Command cmdlet cannot find and display the commands in the module.

The commands in the module are missing from the Show-Command window in Windows PowerShell Integrated Scripting Environment (ISE).

Where to Install Modules

This section explains where in the file system to install Windows PowerShell modules. The location depends on how the module is used.

Installing Modules for a Specific User

If you create your own module or get a module from another party, such as a Windows PowerShell community website, and you want the module to be available for your user account only, install the module in your user-specific Modules directory.

$HOME\Documents\WindowsPowerShell\Modules\<Module Folder>\<Module Files>

The user-specific Modules directory is added to the value of the PSModulePath environment variable by default.

Installing Modules for all Users in Program Files

If you want a module to be available to all user accounts on the computer, install the module in the Program Files location.

$Env:ProgramFiles\WindowsPowerShell\Modules\<Module Folder>\<Module Files>

[!NOTE] The Program Files location is added to the value of the PSModulePath environment variable by default in Windows PowerShell 4.0 and later. For earlier versions of Windows PowerShell, you can manually create the Program Files location (%ProgramFiles%\WindowsPowerShell\Modules) and add this path to your PSModulePath environment variable as described above.

Installing Modules in a Product Directory

If you are distributing the module to other parties, use the default Program Files location described above, or create your own company-specific or product-specific subdirectory of the %ProgramFiles% directory.

For example, Fabrikam Technologies, a fictitious company, is shipping a Windows PowerShell module for their Fabrikam Manager product. Their module installer creates a Modules subdirectory in the Fabrikam Manager product subdirectory.

To enable the Windows PowerShell module discovery features to find the Fabrikam module, the Fabrikam module installer adds the module location to the value of the PSModulePath environment variable.

Installing Modules in the Common Files Directory

If a module is used by multiple components of a product or by multiple versions of a product, install the module in a module-specific subdirectory of the %ProgramFiles%\Common Files\Modules subdirectory.

In the following example, the Fabrikam module is installed in a Fabrikam subdirectory of the %ProgramFiles%\Common Files\Modules subdirectory. Note that each module resides in its own subdirectory in the Modules subdirectory.

Then, the installer assures the value of the PSModulePath environment variable includes the path of the common files modules subdirectory.

Installing Multiple Versions of a Module

To install multiple versions of the same module, use the following procedure.

  1. Create a directory for each version of the module. Include the version number in the directory name.
  2. Create a module manifest for each version of the module. In the value of the ModuleVersion key in the manifest, enter the module version number. Save the manifest file (.psd1) in the version-specific directory for the module.
  3. Add the module root folder path to the value of the PSModulePath environment variable, as shown in the following examples.

To import a particular version of the module, the end-user can use the MinimumVersion or RequiredVersion parameters of the Import-Module cmdlet.

For example, if the Fabrikam module is available in versions 8.0 and 9.0, the Fabrikam module directory structure might resemble the following.

The installer adds both of the module paths to the PSModulePath environment variable value.

When these steps are complete, the ListAvailable parameter of the Get-Module cmdlet gets both of the Fabrikam modules. To import a particular module, use the MinimumVersion or RequiredVersion parameters of the Import-Module cmdlet.

If both modules are imported into the same session, and the modules contain cmdlets with the same names, the cmdlets that are imported last are effective in the session.

Handling Command Name Conflicts

Command name conflicts can occur when the commands that a module exports have the same name as commands in the user’s session.

When a session contains two commands that have the same name, Windows PowerShell runs the command type that takes precedence. When a session contains two commands that have the same name and the same type, Windows PowerShell runs the command that was added to the session most recently. To run a command that is not run by default, users can qualify the command name with the module name.

For example, if the session contains a Get-Date function and the Get-Date cmdlet, Windows PowerShell runs the function by default. To run the cmdlet, preface the command with the module name, such as:

To prevent name conflicts, module authors can use the DefaultCommandPrefix key in the module manifest to specify a noun prefix for all commands exported from the module.

Users can use the Prefix parameter of the Import-Module cmdlet to use an alternate prefix. The value of the Prefix parameter takes precedence over the value of the DefaultCommandPrefix key.

Supporting paths on non-Windows systems

Non-Windows platforms use the colon ( : ) character as a path separator and a forward-slash ( / ) character as a directory separator. The [System.IO.Path] class has static members that can be used to make your code work on any platform:

  • [System.IO.Path]::PathSeparator — returns the character used to separate paths in a PATH environment variable for the host platform
  • [System.IO.Path]::DirectorySeparatorChar — returns the character used to separate directory names with a path for the host platform

Use these static properties to in place of the ; and \ characters when you are constructing path strings.

Установка PowerShell модулей в офлайн режиме (без доступа в Интернет)

date24.08.2021
useritpro
directoryPowerShell, Windows 10, Windows Server 2016
commentsКомментариев пока нет

Большинство популярных модулей PowerShell устанавливаются в онлайн режиме из официального репозитория PowerShell Gallery (PSGallery) с помощью команды Install-Module . Однако, вы не сможете установить нужный модуль PowerShell, если ваш компьютер находится в изолированной от интернета сети или доступ к PSRepository ограничен. Или в сценарии с установкой модуля на сервере, на которых как правило заблокирован прямой доступ в интернет. В этой статье рассмотрим способ офлайн установки модулей PowerShell и импорта модуля с удаленного компьютера на примере модуля для управления SQLServer.

Обратите внимание, что на сайте PowershellGallery.com отсутствуют ссылки на загрузку модулей. Единственное, что вы можете загрузить с сайта это пакет NuGet (файл .nupkg ). С помощью определенных манипуляций вы сможете установить PowerShell модуль из nupkg файла, но это будет не совсем полноценная установка модуля (основная проблема – не устанавливаются зависимости).

Модули POwerShell в psgallery

Ручная установка модуля PowerShell в офлайн системах

Сначала нужно установить нужный вам PowerShell модуль на компьютере, на котором доступ в интернет не ограничен.

Проверьте, что модуль присутствует в галерее PSGallery:

Find-Module –Name *SqlServer*| Select Name, Version, Repository

Find-Module PSGallery

Скачайте нужный вам модуль на ваш компьютер в указанный каталог:

Save-Module –Name SqlServer –Path C:\ps\

Save-Module - скачать powershell модуль из галереи скриптов на локальный диск

Скопируйте папку с модулем на другой компьютер, на котором вы хотите его установить.

Разберемся, в каких каталогах хранятся модули PowerShell:

пути PSModulePath

Как вы видите, PowerShell модули могут хранится по одному из следующих путей:

  • C:\Users\root\Documents\WindowsPowerShell\Modules ( $Home\Documents\PowerShell\Modules ) – модули в этом каталоге в доступны только данному пользователю (CurrentUser)
  • C:\Program Files\WindowsPowerShell\Modules ($Env:ProgramFiles\WindowsPowerShell\Modules) — путь используется при установке модуля для всех пользователей компьютера (-Scope AllUsers)
  • C:\Windows\system32\WindowsPowerShell\v1.0\Modules (каталог для встроенных модулей по-умолчанию)

Скопируйте модуль в каталог C:\Program Files\WindowsPowerShell\Modules .

скопировать каталог с модулем powershell на офлайн компьютер

Проверьте, что модуль SQLServer теперь доступен:

Get-Module -Name SQLServer -ListAvailable

Get-Module

Каталог модуля можно узнать так:

(Get-Module -ListAvailable SQLServer).path

Каталог в котором хранится модуль powershell

Выведите список доступных команд в модуле:

Get-Command -Module SQLServer

Аналогичным образом вы можете установить любой модуль. Я чаще всего использую этот способ для установки PowerShell модуля SQLServer, PSWindowsUpdate и PowerCLI для VMWare.

Импорт PowerShell модуля по сети с другого компьютера

Если вы не хотите устанавливать PowerShell модуль на всех компьютерах, вы можете импортировать любой модуль с другого компьютера по сети с помощью PSRemoting:

$session = New-PSSession -ComputerName msk-sql01

Вывести список установленных модулей на удаленном компьютере:

Get-Module -PSSession $session –ListAvailable

Импортировать указанный модуль на ваш компьютер:

Import-Module -PSsession $session -Name SqlServer

Не забудьте закрыть сессию после окончания:

Еще более интересный способ локально использовать PowerShell модуль, установленный на удаленном компьютере через неявное удаленное управление (Implicit remoting).

Подключитесь к удалённому компьютеру через Invoke-Command и импортируйте нужный вам модуль PowerShell:
$session = New-PSSession -ComputerName msk-sql01
Invoke-Command -Session $session

Экспортируйте командлеты модуля из удаленной сессии в локальный модуль

Export-PSSession -Session $s -CommandName *-Sql* -OutputModule RemSQLServer -AllowClobber

Данная команда создаст на вашем компьютер новый PowerShell модуль RemSQLServer (в каталоге C:\Program Files\WindowsPowerShell\Modules ). Сами командлеты при этом не копируются.

Теперь чтобы использовать командлеты PowerShell из этого модуля достаточно импортировать его в сессию:

Все командлеты модуля SQL теперь доступны без установки явного подключения к удаленному компьютеру. Попробуйте выполнить запрос к MS SQL с помощью Invoke-Sqlcmd. Все команды доступны пока вы не закроете консоль PowerShell или не удалите модуль.

Предыдущая статьяПредыдущая статья Следующая статья Следующая статья

How to Install PowerShell Modules – Step by Step

How to Install PowerShell Modules – Step by Step

Windows PowerShell is a cross-platform task automation solution with an interactive command-line shell that simplifies configurations and automates administrative tasks. Microsoft created Window PowerShell to control and automate the administration tasks run on the Windows Server Environment.

The tool is gaining popularity among sysadmins and experienced Windows users. It helps automate almost any task in the Windows ecosystem.

With the help of its latest version, administrators can easily manage Windows server OS and control Lync-based servers, Exchange, and SQL. A PowerShell comprises a command-line shell, a scripting language, and a configuration management framework that aid in batch processing, script automation, and controlling resources in the cloud.

Compared to VBScript and cmd.exe, Windows PowerShell supports various functions and allows the execution of a .NET code. Also, Windows PowerShell is available in several versions and is easy to learn and implement.

Features of Windows PowerShell

The popular tool is built on the .NET framework, Common Language Runtime, and Dynamic Language Runtime with old CMD functionality and new scripting instruction sets. It comprises various features that make it simple for sysadmins to access and manage the execution of scripts, cmdlets, and language elements.

Here are a few vital features of Windows PowerShell:

  • Windows PowerShell Workflow The Windows PowerShell version 3.0 introduced workflow capabilities that made it easier for sysadmins to perform time-consuming complex tasks. With the help of this feature, sysadmins can now perform complex tasks across multiple devices at different locations.
  • Desired State Configuration Sysadmins can easily configure the software with the help of the DSC feature available in Windows PowerShell. This feature provides a collection of language extensions, resources, and cmdlets that simplifies the configuration process.
  • Background Job Another excellent feature supported by Windows PowerShell is the Background Job. This feature helps users run scripts and cmdlets in the background on the remote and local machines without creating any negative impact on the user interface.
  • The Module cmdlets Using Windows PowerShell remoting, users can import modules and execute cmdlets available on remote computers to the local computers.
  • Scheduled job The scheduled job feature is quite similar to the background job. Under this feature, all the background jobs executed asynchronously are started manually.
  • Script debugging This feature allows users to cross-check the script, function, command, and expressions when running PowerShell. Sysadmins can also manage breakpoints with the help of cmdlets sets supported by the PowerShell script debugger.

In this post, we will show how to install PowerShell Modules on Windows systems.

Install PowerShell Modules Manually

You will need to install the PowerShell module manually if your required module is not available in the PowerShell gallery. Follow the below steps to install the PowerShell module manually.

Step 1 – First, open the PowerShell as an administrator user and find the PowerShell module default installation path using the following command:

You should see the PowerShell module default installation path in the following screen:

powershell install path

Step 2 – Next, download the PowerShell module named PowerNet from the Internet and copy it into the PowerShell default path:

Verify powernet module

Step 3 – Next, run the following command to verify the newly added module visible to PowerShell:

You should see your newly added PowerNet module in the following output:

Step 4 – Next, load the added module to the active memory so you can access it in your current session:

You will get the following warning message:

Type R and press the Enter key to load the module. You will get another error message:

To resolve this error, you must set the execution policy unrestricted. You can set it with the following command:

Install PowerShell Module from PowerShell Gallery

The simple and easiest way to install the PowerShell module is to install it from the PowerShell gallery. Follow the below steps to install the PowerShell module:

Step 1 – First, you will need to install the Nuget package on your system. You can install it by running the following command:

Once installed, you should see the following output:

Step 2 – Next, you will also need to install the PowerShellGet on your system. PowerShellGet is a module that provides commands to find, update and publish modules, scripts and resources. You can install it with the following command:

Step 3 – Now, let’s install the module named NTFSSecurity from the PowerShell gallery using the following command:

You will get the following warning:

Answer Yes to All and press the Enter key to install the NTFSSecurity module.

Step 4 – You can now see the detailed information of the installed module by running the following command:

You will get the following output:

Conclusion

In this post, we explained different ways to install the PowerShell module on Windows. You can now choose your preferred method to install your desired PowerShell module to perform complex administrative tasks with its command-line and script language. The PowerShell tool can work on all major operating systems such as Windows, Linux, and mac OS X.

Understanding and Building PowerShell Modules

Download a free trial of Veeam Backup for Microsoft 365 and eliminate the risk of losing access and control over your data!

Table of Contents

Working with PowerShell modules is an important piece of PowerShell automation. When you start learning PowerShell, the first steps usually are using single commands. This leads to building scripts which then leads to building functions.

Not a reader? Watch this related video tutorial!

By using functions, you can make your scripts more modular. This allows you to be able to use the same code in many places without copying and pasting to code all over the place. Using functions lets you spend less time making the same edit to the same code everywhere it is used. Instead you can work on making your code better in a single place.

To take functions to the next level, you can combine these functions together into a module.

A module is a collection of functions in a text file with a psm1 extension. There are some optional additions, such as a module manifest and comment-based or external help that may also be included. These will be covered later on.

Prerequisites

I’ll be using Windows PowerShell 5.1 in this article. If you’re using an older version or PowerShell Core, your mileage may vary as to results you see.

Interacting with Modules

Once you first open a PowerShell session, you will start off with two modules. The first is Microsoft.PowerShell.Utility which contains many basic PowerShell functions that you use already. The other module is PSReadline. You can see these starting modules by using the Get-Module command.

Listing modules with Get-ModuleListing modules with Get-Module

That said, this is not a complete list of all the modules available. Ever since PowerShell 3, modules that are installed will be imported as needed. If you are running an older version of PowerShell you will be required to use the Import-Module command to first import the module before using any of the commands.

There are times where you would still want to use Import-Module even in later versions. If you wanted to import a module after it is already installed, you can use Import-Module like this:

Importing modules with Import-ModuleImporting modules with Import-Module

While Get-Module will show all the modules that are imported, you will not see modules that have not been imported yet. You can then use the ListAvailable parameter to show all the other modules that are available.

Listing all available modules with Get-Module -ListAvailableListing all available modules with Get-Module -ListAvailable

Not all Commands are Shown By Default

The ExportedCommands property contains a list of all the available commands that are exported from the module. You may see some differences between this list and what is in the module file. Exported commands is a feature built into the module manifest that allows the writer to leave a function as hidden. Module authors may also use the Export-ModuleMember cmdlet but that’s outside the scope of this article.

Module authors may want to have a function hidden because it’s meant to support other functions, not be user-facing. To have a function hidden the author would exclude it from the FunctionsToExport array in the manifest. Here you can see an expanded view of the ExportedCommands property.

Viewing exported commandsViewing exported commands

Importing Modules

There are many ways to start using modules. You can manually import the module using the path to the module files. This allows you to be able to test and update the module without having to do much work. But this doesn’t allow for much portability, since you would have to use the exact path to the module. PowerShell will also not auto-import modules not in the $env:PSModulePath variable.

Selectively Importing Commands

You can use Import-Module to only import specific functions instead of the whole module by using the Function parameter. This can save time when importing modules from remote systems, such as the Office 365 modules.

All User Modules

Modules installed for all users get placed into C:\Program Files\WindowsPowerShell\Modules. This directory contains many pre-added modules including any modules installed using Install-Module using the default scope AllUsers .

Current User Modules

If you are installing a module but only want a single user to use it, there is a CurrentUser scope. This puts the module files in your Documents folder at C:\Users\<username>\Documents\WindowsPowerShell\Modules. This can be useful in an environment where you use folder redirection with the Documents folder.

In this case, you can install a module on one computer and use it on another since they would both be sharing the same documents folder.

System Modules

For completeness, there is also a module directory at C:\Windows\System32\WindowsPowerShell\1.0\Modules. While technically, a module placed in this path would be imported like one of the other paths, but it is not recommended as this is reserved for Microsoft’s system modules.

Naming is Important

You can manually place your module in one of these paths to make it available by default with a new session, but you have to make sure that you follow the required naming for modules. The folder that the module files are placed in, must be the same name as the psm1 module file and the psd1 module manifest if there is one.

Using Get-Module -ListAvailable that we had mentioned prior references these paths. You can see all the module paths using $env:PSModulePath -Split ‘;’ . You may notice other paths in the list than what is shown here. Many programs add their own module paths when they are installed. One of the examples of this is SQL, which has its own modules included in its own module paths.

Viewing module paths with $env:PSModulePathViewing module paths with $env:PSModulePath

There are also some modules that you would install with a different process. One of the most significant examples of this is the ActiveDirectory module. From Windows 7 up to Windows 10 1803, you would install this with the Remote Server Administration Tools (RSAT) installer.

On newer versions of Windows 10 (1809+) this is only available through the Features On Demand. Installing RSAT installs the ActiveDirectory modules and many others that you would use to administer other Windows roles. On Windows server OSs, these modules are installed through the Server Manager.

Importing Remote Modules (Implicit Remoting)

There are some cases where it is not practical to have a module running locally. Instead it is better to connect to a remote device and import a module installed on it. When you do this, the commands are actually executed on the remote machine. This is frequently used with Microsoft’s Office 365 modules. Many of them connect to an Office 365 server that then imports a module. When you run any of the commands, they get run on the remote server and then the output is sent back to your session.

Another use of importing remote modules is when you do not have the module installed locally. This is what you would get if you did not have the ActiveDirectory module installed, but you tried importing it.

Module not installedModule not installed

To import a remote module, you first have to create a PSSession. You can use New-PSSession to create the session. Then you would import the module available on the remote device using the PSSession parameter with Import-Module .

Using this method of importing remote modules allows for faster code execution in a distributed environment. For example, if you are working from your computer, but the servers you are working on are across the US, it may take significantly longer to run certain commands locally against the servers. Whereas running the commands on a server and feeding the output back to your local session is much faster.

Adding a Module Prefix

You can also add a prefix on the functions imported from the remote machine. This option is available while importing local modules, but is rarely used outside of testing different versions of a module side by side.

If you ran the import command above and this is what you would see when you look at the commands:

Viewing all available commands in a moduleViewing all available commands in a module

In this case, you can use a prefix to show that it is not a local module. This can be used in cases where you are importing a module that is also available locally. Adding the prefix reduces confusion on where the code is being executed.

Removing Modules

You can also remove a module from the current session without using Remove-Module . This removes a module from the local session without removing the module files. You may want to use this in a case where you were using a remote session to use a module. You could use Remove-Module to clean up your session and then disconnect the remote session.

Removing a module from the sessionRemoving a module from the session

Another use of Remove-Module is if you are making changes to a module and you do not want to launch a new PowerShell session. In this case, you would use Remove-Module followed by Import-Module to reload it into your session. Alternatively, you can use the Force parameter with Import-Module . This will complete the unload and reload of the module for you.

What Makes up a PowerShell Module

A module can consist of one or more files. To meet the minimum requirements for a module, you must have a module file. This can be a PSM1 file or any other module file such as a binary module file. To build upon that, your psm1 should have functions defined in it, or it will not be much use to anyone.

While there are no requirements for how the functions should look or what they should do, there are some guidelines. It is usually preferred to have all of the functions in a module built around the same concept.

Modules Contain Like-Minded Functions

For example, the ActiveDirectory module only includes functions that interact with Active Directory in some way. Usually the function names also contain a prefix. Going back the ActiveDirectory module as an example, all of the nouns in the function names start with AD.

Using these guidelines helps with discoverability of the functions. Imagine you have just imported this new module and want to tab through the functions. This is much easier to do if all of the functions have a similar name structure. While you may frequently see modules start with PS, this prefix is officially reserved for Microsoft modules only. You probably will not cause an issue if you use PS at the start of your module, you may create a conflict with another module name.

Using these guidelines, if you had a bunch of functions that all had to do with interacting with the registry you could have something like:

Module Manifests

To build on the text module file, you can also include a module manifest. These files have a PSD1 extension and contain metadata about the module. This is where you would include information on the author, description of the module, other required modules, and many other attributes. To publish to a repository, it is required to have the Author and Description fields populated.

Here is an example of a manifest that we may have for our registry module:

While this may look intimidating at first, Microsoft has a handy cmdlet you can use to generate a module manifest. The included command is New-ModuleManifest . To generate the manifest shown above you could used:

External Help Files

You may also see external help files in some modules. They could be identified by the <ModuleName>-Help.xml at the end of the file name. These external help files contain the same information that would normally be contained in the command-based help that you may find in a function definition.

This would also require you to add # .ExternalHelp <ModulePath>-Help.xml to your function to have it work properly when using the Get-Help command after importing the module. It is usually only common to see external help files with very large modules and due to that they are out of the scope.

Related Files

While these are the most common types of files you will see in a module, these are not the only files. Sometimes you will see binary files in addition to a text module as there are other dependencies. By exploring through the module paths, you can find many examples of additional file types in modules.

To have non-standard module files properly publish you would include other files in the FileList parameter in your module manifest.

Within the module manifest, you will notice many other parameters that are currently empty. You can use these to define other requirements for using your module. For example, you can define the versions of PowerShell the module can work with. If you try to import the module on an unsupported version of PowerShell, this is what you would see:

Requiring certain versions of PowerShellRequiring certain versions of PowerShell

PSRepositories

One of the key distribution options for modules is a PSRepository. At a 1000′ view, a PSRepository is a local where multiple people or multiple devices can access the module files. These are frequently web servers where you can publish files.

You can also use a directory for the repository, but this does limit you on the functionality of your repository. You can host a PSRepository yourself, or you can utilize one of the many options available on the internet like the PowerShell Gallery. You can see your PSRepositories by using the Get-PSRepository command.

Default PowerShell NuGet repositoriesDefault PowerShell NuGet repositories

By default, you will only have one entry and it will be for the PowerShell Gallery. You may notice that it will say untrusted. This is because PowerShell makes you aware that by using the PowerShell Gallery you may be using code not written and approved by Microsoft. This means that before any modules are installed from it, you will have to give explicit permission.

Adding PSRepositories

You can also add your own repositories. To trust PowerShell Gallery, you can run Get-PSRepository -Name PSGallery | Set-PSRepository -InstallationPolicy Trusted or you can accept the warning the first time you install a module from the PowerShell Gallery.

All of the commands that you would use to interact with these PSRepositories can be found in the PowerShellGet module. You can see the functions here:

Commands in the PowerShellGet moduleCommands in the PowerShellGet module

The PowerShellGet module may be required to be updated before interacting with certain repositories.

Finding Modules

Another key feature of using a PSRepository is being able to search for modules. This is accomplished using the Find-Module command. There are multiple ways to filter to find specifically what you are looking for, but for now you can search for the VMware modules like this:

Finding modules on the PowerShell GalleryFinding modules on the PowerShell Gallery

This will show all of the modules that start with VMware. While most of these are from VMware, you need to look at the author attribute to see who published the module.

Since anyone can upload to PowerShell Gallery, there are thousands of modules available. This means that you may find modules that do not work properly for your use case. Many modules that you will find are open source so you can contribute to them to improve the functionality of the module.

Installing Modules

To use the Install-Module command, you have to have a trusted PSRepository that is hosting the module. This can be the PowerShell Gallery, another internet PSRepository, or a self-hosted site. You can pipe from the Find-Module command to be available to easily confirm the module before you install it.

Finding modules installed from a PSRepositoryFinding modules installed from a PSRepository

You can also define the version of a module by using the MinimumVersion , MaximumVersion , or RequiredVersion parameters.

To see all of the modules installed using Install-Module you can use Get-InstalledModule . This will list all of the modules installed to the AllUsers scope or your CurrentUser scope.

Uninstalling Modules

Just like you can install a module, you can also uninstall a module. If the module was not installed via the Install-Module command, you can not uninstall it with the Uninstall-Module command.

Uninstalling modules installed from a PSRepository with Uninstall-ModuleUninstalling modules installed from a PSRepository with Uninstall-Module

As you can see here we are trying to uninstall the ActiveDirectory module. Since this module is not installed with Install-Module , you would receive an error when trying to use Uninstall-Module . For you to uninstall this module, we would have to uninstall it through reversing what you used to install the module.

To see a successful uninstall of a module, you can uninstall the VMware.PowerCLI module you installed earlier.

Uninstalling a module downloaded from the PowerShell GalleryUninstalling a module downloaded from the PowerShell Gallery

Even though you uninstalled VMware.PowerCLI, you can see that there are still many dependencies that are installed. If you wanted to uninstall all of the modules we could use Get-InstalledModule VMware.* | Uninstall-Module -Force .

The reason you would have such difficulties fully uninstalling this module is because it has so many dependencies. On top of that, some of these modules are dependencies of each other, which is why the Force parameter would be required.

Updating Modules

Now that you know how to install and uninstall a module, you may be wondering how you update a module that you have installed.

Just like other processes, if the module was not installed using Install-Module , you cannot update the using the PowerShell commands. You can use Update-Module to update a module to the newest release, or to a newer specific version.

There is also a switch to AllowPreRelease which would allow you to update to a version that has not been officially released. Sometimes this can help as there may have been a fix to a bug that you are experiencing or a new feature that was added that you would like to use.

Updating modules with Update-ModuleUpdating modules with Update-Module

Inspecting/Saving a Module

One of the much less used commands that is very helpful when vetting modules before use is Save-Module . Using this command, you can download a module to a path without installing it.

You can then inspect the files and if the module is not a binary module you can open up and look at the code that makes up the module. This can be good not only for making sure a module is not doing anything malicious, but also to learn how others are structuring their modules.

Downloading modules with Save-ModuleDownloading modules with Save-Module

In this example, not only is the VMware.PowerCLI module downloaded, but also all of the dependencies. Here is what shows in the VMware.PowerCLI folder:

VMware.PowerCLI module contentsVMware.PowerCLI module contents

This is a good example of showing how there are sometimes non-standard module files included in the module such as the end user licensing agreement.

Writing your own Module

You have now seen how to interact with someone else’s module. Now you want to learn how to create your own so that you can start optimizing your code for scalability.

Create Template Files

First you need to create a folder for all of your module files. After you have the container, you need to create your module file. You have to make sure that your module file has the same name as your folder or else when trying to publish your module, PowerShell will not discover the module correctly.

Now you also want to use a manifest, you will need to also name it the same as the container and module file.

With the container, module file, and manifest file, you have a full functioning module. You could publish this module to a PSRepository and start installing it anywhere you wanted. Although, since the module file is empty, it probably will not do you much good. You can still use these files to test publishing to make sure your repository works.

Registering a PSRepository

Before you can publish your module, you will need to add another PSRepository to your session. For testing, you can use a local path as your PSRepository since it will be easy to set up and tear down.

Normally, if you were going to set up a PSRepository with a directory, you would want to make sure that multiple computers can access it. You can create a local repository like this:

If you were only downloading from the PSRepository and never publishing, you could exclude the PublishLocation parameter.

Publishing your Module

Since you already set the installation policy to trusted, you will not get a confirmation to allow a module to be installed from the repository. Now that you have a new PSRepository available, you can publish your module using Publish-Module -Name .\Scripts\ATARegistry -Repository LocalRepo .

After publishing your module, you can use the commands from above to find the module and install it.

Now that you have installed the module, you can use Get-Module to see the module imported into your local session. Since you did not add any functions to the FunctionsToExport array in the manifest, the ExportedCommands property is empty.

No exported commandsNo exported commands

Adding to your Module

Now that you know you can publish and install your module, you can start to add some functionality to it. You could add a function to return a registry key so it looks like this:

If you left the manifest as is and tried to upload your new module you would run into two problems. The first is you would receive an error stating that the version of your module already exists on your repository. This is because you have not changed the module version in the manifest file.

Exporting Module Functions

The other problem would be that after you imported the module, you would still see no functions in the ExportedCommands property because you have not added your new function to the manifest.

While your function would be able to be used without listing it in the FunctionsToExport list, it would make it much more difficult to locate.

As long as you do not define an empty array, @() , for your FunctionsToExport all functions, variables, and aliases are exported by default.

To fix these two problems, you can update your module file like this:

Now that you have added a function to your module and you have updated your manifest to reflect these changes, you can publish the new version of your module using the same command as before.

Deciding Between FunctionsToExport and Export-ModuleMember

There are two similar features of PowerShell when exporting module members. The challenge is deciding between the two. Both are correct, but one may work better for you, depending on your needs.

When you are looking to dynamically control what functions are exported, use Export-ModuleMember as you can pass a list of functions to export. Typically, this is used when dot-sourcing multiple individual function PS1 files. By dividing the internal functions into a private folder and exportable functions into a public folder, you can easily export those by passing all public functions to the Export-ModuleMember function.

A few notes about Export-ModuleMember:

  • Overrides the behavior of FunctionsToExport , therefore if an Export-ModuleMember command is used, FunctionsToExport has no effect.
  • Export-ModuleMember does not export variables and aliases without explicitly defining them, unlike FunctionsToExport , which does export those values.
  • Multiple Export-ModuleMember commands may be used and they stack instead of take precedence.

If you do not expect to have changes in your function list, using the FunctionsToExport configuration in the module manifest works fine, and does not require you to explicitly export variables and aliases.

Updating your Module

The last step would be for you to update your module in your session to be able to use the updated files. Using Update-Module ATARegistry you download the update that you just published to the repository.

Exported commands now show upExported commands now show up

Now you can see that you have the new version of the module and you can see the function that you have defined in the manifest.

Building Help Content

One of the options that was passed over earlier is the help system that is built into PowerShell. You have at some point probably used Get-Help on a function. This information can be added in two primary ways.

The first is to add comment-based help into the function definition. This is usually the way that many module writers implement. The other way is to use an external help file. You can use the Full parameter to show everything the help has to offer.

Finding help with Get-HelpFinding help with Get-Help

As you can see, there really is not much information and the little information you do get most likely would not be helpful to anyone.

You can add some comment-based help to your module file to populate these fields in the help system. You can read about all of the options for comment-based help by using Get-Help about_Comment_Based_Help .

For now, you can update your function to look like below. This is a list of the most commonly used help parameters, but all of these are still optional and there are others that could be added instead.

Now your function looks like this:

There are some special help parameters, like .FORWARDHELPTARGETNAME. This option forwards all incoming help requests to a different command. This could be used in a case where the help should show the same information for multiple commands.

Now that you have added the help, you can update the version in the module manifest, publish the new version, and update the installed version for your session like you did earlier.

If you now look at the help for the function, you can see there is much more information available. This is a great way to include documentation on how to use the functions especially for someone who is less experience and may not be able to quickly understand what the module is doing by looking at the code.

Getting full help content with Get-HelpGetting full help content with Get-Help

In the case of an external help file, the information added is the same, but the information is placed in a separate file and linked within the function.

If you look in the AllUsers module path you can see the version of the module and all of the module files that you have been installing.

Folder name is the module versionFolder name is the module version

If you go back to your PSRepository path C:\Repo that you created earlier, you can see a bunch of NUPKG files. There will be one for each version that was published. These are compressed versions of what you published when using Publish-Module .

Summary

Once you’ve got a handle on the PowerShell console, PowerShell as a language and writing scripts, building your own modules is the last step. Modules allow you to begin developing useful tools in PowerShell. If designed and built correctly by creating modules for a single purpose, you’ll inevitably find yourself writing less and less code over time. You’ll start referencing your module functions in more code and building from there.

Module functions allow you to abstract away the code you find yourself repeating in scripts. They represent “labels” to reference later on in code that can be called at any time rather than reinventing the wheel and trying to figure out how you had already accomplished your goal previously. Modules are the final “packaging” of PowerShell code that groups together like-minded code to prevent wasting time on problems you have already solved.

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

More from ATA Learning & Partners

Recommended Resources!

Recommended Resources for Training, Information Security, Automation, and more!

Get Paid to Write!

ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

ATA Learning Guidebooks

ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Luxury Car Rental in Miami | Reserve a Premium Vehicle with RealCar