Jak zainstalować i zarządzać modułami w PowerShellu?

PowerShell i moduły - jak instalować i zarządzać

Czym właściwie jest moduł?

PowerShell instalacja i zarządzanie modułami
Moduł to paczka zawierająca różne komponenty PowerShella (funkcje, cmdlety, zmienne, aliasy, a nawet własne typy obiektów). Moduły pozwalają rozszerzyć możliwości PowerShella.

Dlaczego warto korzystać z modułów?

Reużywalność

Tworzysz kod raz, pakujesz w moduł i możesz używać, kiedy tylko chcesz lub udostępniasz innym.

Porządek

Moduły pomagają utrzymywać kod w czytelnej, modularnej i uporządkowanej formie.

Możliwości

Istnieją tysiące gotowych modułów: od obsługi Azure po automatyzację Active Directory.

Rodzaje modułów

Gdzie PowerShell trzyma moduły?

PS C:\Users\Admin> $env:PSmodulepath -split ';'
C:\Users\Admin\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
PS C:\Users\Admin> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   2.0.0.0    Hyper-V                             {Add-VMAssignableDevice, Add-VMDvdDrive, Add-VMFibreChanne...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     2.0.0      PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...
PS C:\Users\Admin> Get-Module -ListAvailable

    Directory: C:\Users\Admin\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     2.6.0                 QRCodeGenerator                     Core,Desk {New-PSOneQRCodeGeolocation, New-PSOneQ…

    Directory: C:\program files\powershell\7\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   7.0.0.0               CimCmdlets                          Core      {Get-CimAssociatedInstance, Get-CimClas…
Manifest   1.2.5                 Microsoft.PowerShell.Archive        Desk      {Compress-Archive, Expand-Archive}
Manifest   7.0.0.0               Microsoft.PowerShell.Diagnostics    Core      {Get-WinEvent, New-WinEvent, Get-Counte…
Manifest   7.0.0.0               Microsoft.PowerShell.Host           Core      {Start-Transcript, Stop-Transcript}
Manifest   7.0.0.0               Microsoft.PowerShell.Management     Core      {Add-Content, Clear-Content, Get-Clipbo…
Binary     1.1.1                 Microsoft.PowerShell.PSResourceGet  Core,Desk {Compress-PSResource, Find-PSResource, 
PS C:\Users\Admin> Get-Module -ListAvailable -Name ActiveDirectory

    Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   1.0.1.0               ActiveDirectory                     Core,Desk {Add-ADCentralAccessPolicyMember, Add-A…
PS C:\Users\Admin> Get-Command -Module ActiveDirectory

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Add-ADCentralAccessPolicyMember                    1.0.1.0    ActiveDirectory
Cmdlet          Add-ADComputerServiceAccount                       1.0.1.0    ActiveDirectory
Cmdlet          Add-ADDomainControllerPasswordReplicationPolicy    1.0.1.0    ActiveDirectory
Cmdlet          Add-ADFineGrainedPasswordPolicySubject             1.0.1.0    ActiveDirectory
Cmdlet          Add-ADGroupMember                                  1.0.1.0    ActiveDirectory
Cmdlet          Add-ADPrincipalGroupMembership                     1.0.1.0    ActiveDirectory
PS C:\Users\Admin> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Manifest   1.0.0.0    NetTCPIP                            {Find-NetRoute, Get-NetCompartment, Get-NetIPAddress, Get-...
Script     2.0.0      PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...


PS C:\Users\Admin> Remove-Module NetTCPIP
PS C:\Users\Admin> Get-Module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     2.0.0      PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...

Instalacja modułów z internetu (PowerShell Gallery)

PS C:\Users\Admin> Find-Module -Name Burnttoast

Version              Name                                Repository           Description
-------              ----                                ----------           -----------
1.1.0                BurntToast                          PSGallery            Module for creating and displaying Toast…
PS C:\Users\Admin> Install-Module -Name BurntToast -Verbose
VERBOSE: Using the provider 'PowerShellGet' for searching packages.
VERBOSE: The -Repository parameter was not specified.  PowerShellGet will use all of the registered repositories.
VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
VERBOSE: The specified Location is 'https://www.powershellgallery.com/api/v2' and PackageManagementProvider is 'NuGet'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='BurntToast'' for ''.
VERBOSE: Total package yield:'1' for the specified package 'BurntToast'.
VERBOSE: Performing the operation "Install-Module" on target "Version '1.1.0' of module 'BurntToast'".
VERBOSE: The installation scope is specified to be 'CurrentUser'.
VERBOSE: The specified module will be installed in 'C:\Users\Admin\Documents\PowerShell\Modules'.
VERBOSE: The specified Location is 'NuGet' and PackageManagementProvider is 'NuGet'.
VERBOSE: Downloading module 'BurntToast' with version '1.1.0' from the repository 'https://www.powershellgallery.com/api/v2'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='BurntToast'' for ''.
VERBOSE: InstallPackage' - name='BurntToast', version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\1205399831'
VERBOSE: DownloadPackage' - name='BurntToast', version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\1205399831\BurntToast.1.1.0\BurntToast.1.1.0.nupkg', uri='https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'
VERBOSE: Downloading 'https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'.
VERBOSE: Completed downloading 'https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'.
VERBOSE: Completed downloading 'BurntToast'.
VERBOSE: InstallPackageLocal' - name='BurntToast', version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\1205399831'
VERBOSE: Validating the 'BurntToast' module contents under 'C:\Users\Admin\AppData\Local\Temp\1205399831\BurntToast.1.1.0' path.
VERBOSE: Test-ModuleManifest successfully validated the module manifest file 'C:\Users\Admin\AppData\Local\Temp\1205399831\BurntToast.1.1.0'.
VERBOSE: Validating the authenticode signature and publisher of the catalog file or module manifest file of the module 'BurntToast'.
VERBOSE: Catalog file 'BurntToast.cat' is not found in the contents of the module 'BurntToast' being installed.
VERBOSE: Checking for possible command collisions for the module 'BurntToast' commands.
VERBOSE: Module 'BurntToast' was installed successfully to path 'C:\Users\Admin\Documents\PowerShell\Modules\BurntToast\1.1.0'.
PS C:\Windows\System32> Get-Module -ListAvailable

    Directory: C:\Users\Admin\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     5.3.1                 Az.Accounts                         Core,Desk {Disable-AzDataCollection, Disable-AzCo…
Script     3.0.0                 Az.Advisor                          Core,Desk {Disable-AzAdvisorRecommendation, Enabl…
Script     7.0.0                 Az.Aks                              Core,Desk {Disable-AzAksAddOn, Enable-AzAksAddOn,…
Script     1.2.0                 Az.AnalysisServices                 Core,Desk {Add-AzAnalysisServicesAccount, Export-…
Script     4.1.0                 Az.ApiManagement                    Core,Desk {Add-AzApiManagementApiToGateway, Add-A…
Script     2.0.1                 Az.App                              Core,Desk {Disable-AzContainerAppRevision, Enable…
Script     2.0.1                 Az.AppConfiguration                 Core,Desk {Clear-AzAppConfigurationDeletedStore, …
Script     3.0.0                 Az.ApplicationInsights              Core,Desk {Get-AzApplicationInsights, Get-AzAppli…
Script     2.0.0                 Az.ArcResourceBridge                Core,Desk {Get-AzArcResourceBridge, Get-AzArcReso…
Script     1.0.0                 Az.ArizeAI                          Core,Desk {Get-AzArizeAIOrganization, New-AzArize…
Script     3.0.0                 Az.Attestation                      Core,Desk {Add-AzAttestationPolicySigner, Get-AzA…
Script     2.0.0                 Az.Automanage                       Core,Desk {Get-AzAutomanageBestPractice, Get-AzAu…
Script     1.11.2                Az.Automation                       Core,Desk {Export-AzAutomationDscConfiguration, E…
Script     4.0.0                 Az.Batch                            Core,Desk {Disable-AzBatchAutoScale, Disable-AzBa…
Script     2.2.0                 Az.Billing                          Core,Desk {Get-AzBillingAccount, Get-AzBillingInv…
Script     6.0.0                 Az.Cdn                              Core,Desk {Add-AzCdnEdgeActionAttachment, Clear-A…
Script     2.1.1                 Az.CloudService                     Core,Desk {Get-AzCloudService, Get-AzCloudService…
Script     1.16.0                Az.CognitiveServices                Core,Desk {Add-AzCognitiveServicesAccountNetworkR…
Script     1.1.0                 BurntToast                          Desk      {Get-BTHeader, Get-BTHistory, New-BTAct…
Script     2.6.0                 QRCodeGenerator                     Core,Desk {New-PSOneQRCodeGeolocation, New-PSOneQ…
PS C:\Users\Admin> Get-InstalledModule

Version              Name                                Repository           Description
-------              ----                                ----------           -----------
5.3.1                Az.Accounts                         PSGallery            Microsoft Azure PowerShell - Accounts cr…
3.0.0                Az.Advisor                          PSGallery            Microsoft Azure PowerShell: Advisor cmdl…
7.0.0                Az.Aks                              PSGallery            Microsoft Azure PowerShell - Azure manag…
1.2.0                Az.AnalysisServices                 PSGallery            Microsoft Azure PowerShell - Analysis Se…
4.1.0                Az.ApiManagement                    PSGallery            Microsoft Azure PowerShell - Api Managem…
2.0.1                Az.App                              PSGallery            Microsoft Azure PowerShell: App cmdlets
2.0.1                Az.AppConfiguration                 PSGallery            Microsoft Azure PowerShell: AppConfigura…
3.0.0                Az.ApplicationInsights              PSGallery            Microsoft Azure PowerShell: ApplicationI…
2.0.0                Az.ArcResourceBridge                PSGallery            Microsoft Azure PowerShell: ArcResourceB…
1.0.0                Az.ArizeAI                          PSGallery            Microsoft Azure PowerShell: ArizeAI cmdl…
3.0.0                Az.Attestation                      PSGallery            Microsoft Azure PowerShell - Attestation…
2.0.0                Az.Automanage                       PSGallery            Microsoft Azure PowerShell: Automanage c…
1.11.2               Az.Automation                       PSGallery            Microsoft Azure PowerShell - Automation …
4.0.0                Az.Batch                            PSGallery            Microsoft Azure PowerShell - Batch servi…
2.2.0                Az.Billing                          PSGallery            Microsoft Azure PowerShell - Billing ser…
6.0.0                Az.Cdn                              PSGallery            Microsoft Azure PowerShell: Cdn cmdlets
2.1.1                Az.CloudService                     PSGallery            Microsoft Azure PowerShell: CloudService…
1.16.0               Az.CognitiveServices                PSGallery            Microsoft Azure PowerShell - Cognitive S…
1.1.0                BurntToast                          PSGallery            Module for creating and displaying Toast…
2.6.0                QRCodeGenerator                     PSGallery            creates QR codes offline

Aktualizacja i usuwanie modułów

PS C:\Users\Admin> Update-Module -Name BurntToast -Verbose
VERBOSE: Checking for updates for module 'BurntToast'.
VERBOSE: Suppressed Verbose Repository details, Name = 'PSGallery', Location =
'https://www.powershellgallery.com/api/v2'; IsTrusted = 'True'; IsRegistered = 'True'.
VERBOSE: Repository details, Name = 'PSGallery', Location = 'https://www.powershellgallery.com/api/v2'; IsTrusted =
'True'; IsRegistered = 'True'.
VERBOSE: Using the provider 'PowerShellGet' for searching packages.
VERBOSE: Using the specified source names : 'PSGallery'.
VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
VERBOSE: The specified Location is 'https://www.powershellgallery.com/api/v2' and PackageManagementProvider is 'NuGet'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='BurntToast'' for ''.
VERBOSE: Total package yield:'1' for the specified package 'BurntToast'.
VERBOSE: Performing the operation "Update-Module" on target "Version '0.8.5' of module 'BurntToast', updating to
version '1.1.0'".
VERBOSE: The installation scope is specified to be 'CurrentUser'.
VERBOSE: The specified module will be installed in 'C:\Users\Admin\Documents\WindowsPowerShell\Modules'.
VERBOSE: An update for the module 'BurntToast' was found with version '1.1.0'.
VERBOSE: The specified Location is 'NuGet' and PackageManagementProvider is 'NuGet'.
VERBOSE: Downloading module 'BurntToast' with version '1.1.0' from the repository
'https://www.powershellgallery.com/api/v2'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='BurntToast'' for ''.
VERBOSE: InstallPackage' - name='BurntToast', version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\434968056'
VERBOSE: DownloadPackage' - name='BurntToast',
version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\434968056\BurntToast.1.1.0\BurntToast.1.1.0.nupkg',
uri='https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'
VERBOSE: Downloading 'https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'.
VERBOSE: Completed downloading 'https://www.powershellgallery.com/api/v2/package/BurntToast/1.1.0'.
VERBOSE: Completed downloading 'BurntToast'.
VERBOSE: Hash for package 'BurntToast' does not match hash provided from the server.
VERBOSE: InstallPackageLocal' - name='BurntToast',
version='1.1.0',destination='C:\Users\Admin\AppData\Local\Temp\434968056'
VERBOSE: Validating the 'BurntToast' module contents under
'C:\Users\Admin\AppData\Local\Temp\434968056\BurntToast.1.1.0' path.
VERBOSE: Test-ModuleManifest successfully validated the module manifest file
'C:\Users\Admin\AppData\Local\Temp\434968056\BurntToast.1.1.0'.
VERBOSE: Validating the authenticode signature and publisher of the catalog file or module manifest file of the module
'BurntToast'.
VERBOSE: Catalog file 'BurntToast.cat' is not found in the contents of the module 'BurntToast' being installed.
VERBOSE: For publisher validation, current module 'BurntToast' with version '1.1.0' with publisher name '' from root
certificate authority ''. Is this module signed by Microsoft: 'False'.
VERBOSE: For publisher validation, using the previously-installed module 'BurntToast' with version '0.8.5' under
'C:\Users\Admin\Documents\WindowsPowerShell\Modules\BurntToast\0.8.5' with publisher name '' from root certificate
authority ''. Is this module signed by Microsoft: 'False'.
VERBOSE: Checking for possible command collisions for the module 'BurntToast' commands.
VERBOSE: Module 'BurntToast' was installed successfully to path
'C:\Users\Admin\Documents\WindowsPowerShell\Modules\BurntToast\1.1.0'.
PS C:\Users\Admin> Get-Module -ListAvailable | ? name -like 'BurntToast'


    Directory: C:\Users\Admin\Documents\WindowsPowerShell\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.1.0      BurntToast                          {Get-BTHeader, Get-BTHistory, New-BTAction, New-BTAudio...}
Script     0.8.5      BurntToast                          {Get-BTHistory, New-BTAction, New-BTAppId, New-BTAudio...}
PS C:\Users\Admin> Uninstall-Module -Name BurntToast -Verbose
VERBOSE: Performing the operation "Uninstall-Module" on target "Version '1.1.0' of module 'BurntToast'".
VERBOSE: Successfully uninstalled the module 'BurntToast' from module base
'C:\Users\Admin\Documents\WindowsPowerShell\Modules\BurntToast\1.1.0'.
PS C:\Users\Admin> Uninstall-Module -Name BurntToast -RequiredVersion 0.8.5
VERBOSE: Performing the operation "Uninstall-Module" on target "Version '0.8.5' of module 'BurntToast'".
VERBOSE: Successfully uninstalled the module 'BurntToast' from module base
'C:\Users\Admin\Documents\WindowsPowerShell\Modules\BurntToast\0.8.5'.

Moduł jest zainstalowany, ale PowerShell go nie widzi

$env:PSModulePath -split ';'

PowerShell ładuje nie tę wersję modułu

Get-Module -ListAvailable -Name <TwójModuł>
Import-Module -Name <TwójModuł> -RequiredVersion <TwojaWersja>

Po aktualizacji modułu stara wersja nadal jest ładowana

(Get-Module -Name &lt;TwójModuŁ>).Path
Uninstall-Module -Name &lt;TwójModuł> -RequiredVersion &lt;wersja>

Moduł jest załadowany i nie da się go nadpisać albo przeładować

Remove-Module -Name MyTools
Import-Module .\\MyTools.psm1 -Force
Install-Module -Name Az -Scope CurrentUser
$env:PSModulePath -split ';'
Get-Command Get-Info | Select-Object Name, ModuleName, Source
ModuleX\Get-Info
Import-Module -Name ModuleX -Prefix X
Get-XInfo

Podsumowanie


To wszystko na dziś!

Jeśli masz ciekawe spostrzeżenia lub doświadczenia w tym temacie – koniecznie podziel się nimi w komentarzach.
A jeśli moje materiały są dla Ciebie pomocne, możesz postawić mi wirtualną kawę.

Dzięki za wsparcie!

Postaw mi kawę na buycoffee.to

Adam Pietrzak

Administrator | Trener i autor szkoleń | Entuzjasta PowerShella

Administrator systemów i sieci wsparcia działań wojskowych z ponad 10-letnim doświadczeniem. Praktyk w dziedzinie zarządzania Active Directory, bezpieczeństwa systemu Windows oraz automatyzacji zadań (PowerShell). Trener i twórca materiałów edukacyjnych (szkolenia, warsztaty, artykuły, podręczniki). Pasjonat dzielenia się wiedzą i wspierania początkujących administratorów IT. Prywatnie – amator aktywnego wypoczynku i rodzinnych podróży.


PowerShell - 10 sposobów na optymalizację codziennej pracy
Podziel się

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *