Avoiding Global Variables in PowerShell Using Dynamic Coverage
PowerShell implements Dynamic Scaling . These days, this is a rare choice in the design of languages, but correctly applied dynamic scaling gives the developer much better control over name conflicts than global variables. To understand how this applies to your case, let's look at the following toy module:
# File Module1.psm1 $module = "Module1" $Context = "User" function Log-Message( $message ) { Write-Host "$module/${action}: $message ($LogLevel-$Context)" } function CommonCode { Log-Message "In CommonCode" } function Invoke-Rollout( $LogLevel = "Terse", $Context=$script:Context) { $action = "Rollout" CommonCode } function Invoke-Remove( $LogLevel = "Terse", $Context=$script:Context) { $action = "Remove" CommonCode } function Set-Module1( $Context=$script:Context ) { $script:Context = $Context } Export-ModuleMember -Function Invoke-Rollout, Invoke-Remove, Set-Module1
The important thing is that in Log-Message variables $module , $action , $LogLevel and $LogContext are not global variables, instead they are free variables, not yet defined. At run time, PowerShell will dynamically determine its binding based on the most recent definition in the call stack ...
Instead of trying to explain it in detail, you might be best off playing with this toy module and see what affects the dynamic definition of the logging area. Here are some experiments I tried:
PS C:\temp> Import-Module -Force .\Module1.psm1 PS C:\temp> Invoke-Rollout Module1/Rollout: In CommonCode (Terse-User) PS C:\temp> # For Sticky Change -- Set-Module1 PS C:\temp> Set-Module1 -Context Machine PS C:\temp> Invoke-Rollout Module1/Rollout: In CommonCode (Terse-Machine) PS C:\temp> Invoke-Remove -LogLevel Verbose -Context XXX Module1/Remove: In CommonCode (Verbose-XXX) PS C:\temp> Invoke-Remove -Context User Module1/Remove: In CommonCode (Terse-User) PS C:\temp> $Context = "FooBar" # This should have no effet on Module1 PS C:\temp> Invoke-Remove Module1/Remove: In CommonCode (Terse-Machine)
source share