PowerShell scope clash when dot sourcing scripts

Question:

I’m having some scope issues when dot sourcing powershell scripts.
Suppose I have one script ‘A.ps1’:

And a script B.ps1

The output of running A.ps1 will be:

Why this happens is quite obvious. The $VERSION variable from B.ps1 is put into the scope of A.ps1 and overwrites that variable. Indeed, this happens with Write-Version as well, but here A.ps1 overwrites B’s version, but because Write-Version is called in B.ps1 before that happens, we can still see the output of B’s Write-Version function.

The question, of course, is how to prevent this?? I’ve tried various scope options, but this doesn’t seem to work when dot-sourcing. And since there are functions in B.ps1 that I do need in A’s scope, just invoking B.ps1 is probably not an option.

Does anyone have any ideas?

Answer:

You can do it by making B.ps1 a module and renaming it to B.psm1. Add Export-ModuleMember to make your functions available to other scripts.

This would be B.psm1:

And A.ps1 would be:

Source:

PowerShell scope clash when dot sourcing scripts by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply