I have a collection of utility functions and other code that I dot-source into every powershell file I write. Having gotten bit by caller scope variables influencing it, I started looking into changing it into a powershell module.
I ran into problems with a couple of the special things I do in it where I actually do want some interaction between the scopes. I'm wondering if there is anyway to "get at" the scope of a module's caller to keep this functionality while moving to a powershell module?
If not, is my best path forward to keep these more specialized things in a dot-sourced file and move the more traditional utility functions into a module? Here are the things that don't easily move to a module:
Setting strict mode and error action preferences to keep sane, e.g.:
Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $PSDefaultParameterValues['*:ErrorAction']='Stop'
This (as expected) has no effect on the caller's environment when the code is run from a .psm1 powershell module. Is there any way to cross from the psm1 scope to the caller scope to make these changes?
Printing out information about the top-level script call, e.g.:
$immediateCallerPath = Get-Variable -scope 1 -name PSCommandPath -ValueOnly Write-Host "Starting script at $immediateCallerPath" $boundParameters = Get-Variable -scope 1 -name PSBoundParameters -ValueOnly Write-Host "Bound parameters are:" foreach($psbp in $boundParameters.GetEnumerator()) { "({0},{1})" -f $psbp.Key,$psbp.Value | Write-Host }
Likewise, these commands can no longer see the top-most calling scope once placed in a .psm1 file