Private/Test/Test-IsModuleLoaded.ps1
|
function Test-IsModuleLoaded { <# .SYNOPSIS Tests if a PowerShell module is currently loaded in the session. .DESCRIPTION Checks if the specified PowerShell module is currently imported and loaded in the active PowerShell session. This does not check if the module is installed on the system, only if it has been imported with Import-Module or loaded automatically. Use this function to determine if a module needs to be imported before using its commands. .PARAMETER Name The name of the module to check. This is case-insensitive and supports wildcards if needed. .INPUTS System.String You can pipe a module name to this function. .OUTPUTS System.Boolean Returns $true if the module is currently loaded in the session. Returns $false if the module is not loaded. .EXAMPLE Test-IsModuleLoaded -Name 'ActiveDirectory' Returns $true if the ActiveDirectory module is currently loaded. .EXAMPLE if (-not (Test-IsModuleLoaded -Name 'Pester')) { Import-Module Pester -ErrorAction Stop } Imports the Pester module only if it's not already loaded. .EXAMPLE $modules = @('ActiveDirectory', 'GroupPolicy', 'DnsServer') $modules | ForEach-Object { if (Test-IsModuleLoaded -Name $_) { Write-Host "$_ is loaded" } } Checks multiple modules to see which are currently loaded. .NOTES This function checks only loaded modules, not installed modules. To check if a module is installed (available) on the system, use Get-Module -Name <ModuleName> -ListAvailable instead. .LINK https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/get-module #> [CmdletBinding()] [OutputType([bool])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string]$Name ) #requires -Version 5.1 process { Write-Verbose "Checking if module '$Name' is currently loaded in session" try { # Check if the module is currently loaded in the session $result = [bool](Get-Module -Name $Name -ErrorAction Stop) Write-Verbose "Module '$Name' loaded status: $result" $result } catch { $errorRecord = [System.Management.Automation.ErrorRecord]::new( $_.Exception, 'ModuleLoadedCheckFailed', [System.Management.Automation.ErrorCategory]::NotSpecified, $Name ) $PSCmdlet.WriteError($errorRecord) return $false } } } |