2
votes

I have a Module Manifest File [.psd1 file] via which I import nested modules [.psm1 files]. One of the modules [.psm1] file defines a constant variable in global scope like this -

set-variable -name DataDirectory -option Constant -value "DataSources" -scope global -description "Data Directory"

When I do remove-module of the psd1 file & then again try to do a import-module in the same session of the Powershell ISE, I get the following error -

+ set-variable <<<<  -name DataDirectory -option Constant -value "DataSources" -scope global -description "Data Directory"
    + CategoryInfo          : WriteError: (DataDirectory:String) [Set-Variable], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand

which means that the variables defined in one of the nested modules have not been unloaded.

Do I have to explicit do a remove-variable ? I thought remove-module will unload everything

1

1 Answers

4
votes

Remove-Module will unload everything defined in the module scope. Only the module that defined the variable can remove it. Global variables will not remove when the module is unloaded. In addition, outside the module scope, you cannot remove a constant variable with Remove-Variable. One thing you can try is testing if the variable already exist before you try creating it.