How to change an item in an imported module - without editing the actual module

Viewed 70

I have an imported module that I am using in another PowerShell script. For this specific script, I need one small change made to a variable within this imported module. Is there a way to import a module, and then override a specific item/variable with a new value, within the script? For example below:

function testmodule{
$test1 = "this is a test"

$test2 = "this is a second test"

echo $test1, $test2
}

Lets say i'm importing the above as a module into a script. How would I override $test2 is a new script without editing the module? I was thinking of something like testmodule.$test2 = "this is the override"

And the output in the script that imports the module would be "this is a test" "this is the override"

1 Answers

You can import the module with a custom prefix and override the needed function; this way you can use the original function in the same script without any problem.

According to the following link: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/import-module?view=powershell-7.2

Example 6: Import the members of a module and add a prefix

This example imports the PSDiagnostics module into the current session, adds a prefix to the member names, and then displays the prefixed member names. The Prefix parameter of Import-Module adds the x prefix to all members that are imported from the module. The prefix applies only to the members in the current session. It does not change the module. The PassThru parameter returns a module object that represents the imported module.

Import-Module PSDiagnostics -Prefix x -PassThru

ModuleType Version    Name               ExportedCommands
---------- -------    ----               ----------------
Script     6.1.0.0    PSDiagnostics      {Disable-xPSTrace, Disable-xPSWSManCombinedTrace, Disable-xW...

Get-Command -Module PSDiagnostics

CommandType     Name                                   Version    Source
-----------     ----                                   -------    ------
Function        Disable-xPSTrace                       6.1.0.0    PSDiagnostics
Function        Disable-xPSWSManCombinedTrace          6.1.0.0    PSDiagnostics
Function        Disable-xWSManTrace                    6.1.0.0    PSDiagnostics
Function        Enable-xPSTrace                        6.1.0.0    PSDiagnostics
Function        Enable-xPSWSManCombinedTrace           6.1.0.0    PSDiagnostics
Function        Enable-xWSManTrace                     6.1.0.0    PSDiagnostics
Function        Get-xLogProperties                     6.1.0.0    PSDiagnostics
Function        Set-xLogProperties                     6.1.0.0    PSDiagnostics
Function        Start-xTrace                           6.1.0.0    PSDiagnostics
Function        Stop-xTrace                            6.1.0.0    PSDiagnostics
Related