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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access