The OnRemove event

The ModuleInfo object provides access to an OnRemove event handler. This event is triggered if the module is removed from the user's session using the Remove-Module command. The event is not triggered if the session is closed. This event handler may be used to trigger a cleanup of the artifacts created by the module, if any are required.

The following module creates a global variable in the user's scope. Exporting the variable from the module using VariablesToExport and Export-ModuleMember may have been a better approach, the variable would have been automatically removed. An OnRemove handler is added to the module to forcefully remove the global variable with the module and the handler is created in the root module file:

$Global:VariableName = 'Value'
$executionContext.SessionState.Module.OnRemove = {
if (Test-Path variable:VariableName) {
Remove-Variable VariableName -Scope Global
}
}

If the preceding module content is placed in TestOnRemove.psm1, and the module file is imported, the VariableName variable will be present:

PS> Get-Variable VariableName

Name Value
---- -----
VariableName Value

When the module is removed, using Remove-Module, the variable is removed as well:

PS> Remove-Module TestOnRemove
PS> Test-Path variable:VariableName
False

Remove-Module and the OnRemove event handler cannot overcome limitations such as the inability to unload assemblies. If the module contains an assembly, .dll file, and that is loaded by the module; the assembly will remain loaded until the PowerShell session is closed.

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

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