Accessing module scope

It is possible to access module scope from the global scope by passing a module information object to the call operator.

The following snippet is used to demonstrate accessing module scope. The module consists of one public function, one private function, and a module-scoped variable:

function GetModuleServiceConnection {
[CmdletBinding()]
param ( )

$Script:connection
}

function Connect-ModuleService {
[CmdletBinding()]
param (
[String]$Name
)

$Script:connection = $Name
}

$Script:connection = 'DefaultConnection'

Export-ModuleMember -Function Connect-ModuleService

The following snippet should be saved to a file named ModuleService.psm1, then the module should be imported using Import-Module .ModuleService.psm1.

By default, only the Connect-ModuleService function is available. The value of the script/module-scoped connection variable may be retrieved as follows:

PS> & (Get-Module ModuleService) { $connection }
DefaultConnection

If the Connect-ModuleService command is used, the value returned by the preceding command will change. The same approach may be used to interact with functions that are not normally exported by the module. For example, the GetModuleServiceConnection function can be called:

& (Get-Module ModuleService) { GetModuleServiceConnection }

Finally, as the command is executing in the scope of the module, this technique may be applied to list the commands within the module, as follows:

& (Get-Module ModuleService) { Get-Command -Module ModuleService }

This technique is useful when debugging modules that heavily utilize module scope.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.195