How can I redefine a function that was exported by a powershell module

Question:

Is there a way that I can re-define a function that was exported by a module and is used by another?

Given the following folder structure:

And the following content for each file:

MyScript.ps1:

Deployment.psm1:

and Logging.psm1:

The output is:

but I would like it to be:

I realize that a better implementation of the Logging module would allow me to control the log level, but that’s not the point of this question: is it possible to redefine/override Log-Debug so that it is a no-op?

As noted in the source of MyScript.ps1, I have tried to redefine the function using Set-Item and just redeclaring the function to no avail….

Answer:

I would’ve guessed that simply defining an empty function with the same name should suffice. And it actually does, when both modules are imported directly in PowerShell:

But for some reason you cannot re-define or remove a function that was imported from a module by another module (or at least I didn’t find a way to do so).

However, you should be able to override the function by making use of command precedence. Since aliases are evaluated first, you can define an alias Log-Debug to a custom logging function:

That way you can even change the logging implementation on the fly, or switch back and forth between original and custom logging function:


Edit:

To make this work in a script you need to define both function and alias as global objects:

Source:

How can I redefine a function that was exported by a powershell module by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply