BudiBadu Logo
Samplebadu

PowerShell by Example: Modules

PowerShell 7

Organizing and distributing PowerShell code with this sample code demonstrating module import, command discovery within modules, module creation with .psm1 files, Export-ModuleMember for public interfaces, and PowerShell Gallery integration.

Code

# Import a module (system or custom)
Import-Module Pester -ErrorAction SilentlyContinue

# List available commands in a module
Get-Command -Module Microsoft.PowerShell.Management

# Check if a module is loaded
if (Get-Module -Name "Pester") {
    Write-Host "Pester is loaded"
}

# Creating a simple module (.psm1 file)
# function My-Func { ... }
# Export-ModuleMember -Function My-Func

# Installing from PSGallery
# Install-Module -Name Az -Scope CurrentUser

Explanation

PowerShell modules are self-contained packages that bundle related functionalities including cmdlets, functions, variables, aliases, and other resources into a convenient unit. Modules can be script modules written as .psm1 files containing PowerShell code, binary modules compiled from C# as .dll files, or manifest modules with .psd1 metadata files describing module properties, dependencies, and exported members.

Modules are loaded into the current session using Import-Module, which makes their exported members available. PowerShell 3.0+ supports module auto-loading where modules are automatically imported when you use their commands. The Export-ModuleMember cmdlet controls which functions, cmdlets, variables, and aliases are publicly accessible, allowing internal helper functions to remain private. Module manifests provide metadata including version numbers, author information, required PowerShell version, and module dependencies.

The PowerShell Gallery serves as the central repository for PowerShell modules, similar to npm for Node.js or PyPI for Python. The Find-Module cmdlet searches the gallery, Install-Module downloads and installs modules, Update-Module upgrades to newer versions, and Uninstall-Module removes modules. Modules can be installed at different scopes: AllUsers (system-wide) or CurrentUser (user-specific), with the latter not requiring administrator privileges.

Code Breakdown

2
Import-Module loads module members into current session.
5
Get-Command -Module discovers cmdlets and functions in module.
8
Get-Module -Name checks if module is currently loaded.
16
Install-Module downloads module from PowerShell Gallery.