Search code examples
powershellpowershell-module

Access PowerShell script parameters from inside module


I have a PowerShell module that contains a number of common management and deployment functions. This is installed on all our client workstations. This module is called from a large number of scripts that get executed at login, via scheduled tasks or during deployments.

From within the module, it is possible to get the name of the calling script:

function Get-CallingScript {
    return ($script:MyInvocation.ScriptName)
}

However, from within the module, I have not found any way of accessing the parameters originally passed to the calling script. For my purposes, I'd prefer to access them in the form of a dictionary object, but even the original command line would do. Unfortunately, given my use case, accessing the parameters from within the script and passing them to the module is not an option.

Any ideas? Thank you.


Solution

  • From about_Scopes:

    Sessions, modules, and nested prompts are self-contained environments, but they are not child scopes of the global scope in the session.

    That being said, this worked for me from within a module:

    $Global:MyInvocation.UnboundArguments
    

    Note that I was calling my script with an unnamed parameter when the script was defined without parameters, so UnboundArguments makes sense. You might need this instead if you have defined parameters:

    $Global:MyInvocation.BoundParameters