Private/Get/Get-ModuleThatLoadedThisFunction.ps1
|
function Get-ModuleThatLoadedThisFunction { <# .SYNOPSIS Gets the name of the module that loaded this function. .DESCRIPTION This function examines the call stack to determine which module loaded and is executing the current function. It looks at the calling script file path and matches it against loaded modules to identify the parent module. This is useful for functions that need to know their own module context. .INPUTS None .OUTPUTS System.String Returns the name of the module that loaded this function, or $null if not called from a module. .EXAMPLE Get-ModuleThatLoadedThisFunction Returns the name of the module, e.g., "Locksmith2" .EXAMPLE $moduleName = Get-ModuleThatLoadedThisFunction if ($moduleName) { Write-Host "Running from module: $moduleName" } Gets the module name and uses it in logic. .LINK https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-pscallstack #> [CmdletBinding()] param ( ) #requires -Version 5.1 try { # Get the call stack to examine where this function was called from $callStack = Get-PSCallStack # The first item is this function, the second is the caller # We want to find which module contains the calling script if ($callStack.Count -gt 1) { $callerScriptName = $callStack[1].ScriptName Write-Verbose "Caller script: $callerScriptName" # Get all loaded modules and find which one contains this script $modules = Get-Module foreach ($module in $modules) { # Check if the caller script path is within the module's path if ($callerScriptName -and $module.Path -and $callerScriptName -like "$($module.ModuleBase)*") { Write-Verbose "Found module: $($module.Name)" return $module.Name } } } # If we couldn't determine the module, return null Write-Verbose "Could not determine the calling module" return $null } catch { $errorRecord = [System.Management.Automation.ErrorRecord]::new( $_.Exception, 'ModuleDetectionFailed', [System.Management.Automation.ErrorCategory]::NotSpecified, $null ) $PSCmdlet.WriteError($errorRecord) return $null } } |