PowerShell 5.1 - How to uninstall module which is currently use
The problem could be that your existing PowerShell session is "locking" the module by loading possible elements from it (such as global variables or constants) even though you are trying to unload it (Remove-Module
).
The cleanest way to be sure it isn't locked is to exit the PowerShell session. If you need to keep the session around to do "stuff" afterwards, trying starting a new PowerShell session (nested session) just before you make use of the module, then exit it at the end.
As mentioned in the original answer by E Bekker, modules may get stuck in session.Closing the PowerShell session, and running uninstall in a new one should help.
Handling auto-loading
As Keith mentioned, a module may get locked if it's auto-loaded. If it happens via profile, adding -NoProfile
to the uninstall script should help:
powershell -NoProfile -Command "Uninstall-Module X"
Some modules, like PSReadLine, get loaded even in such session, and may require extra -NonInteractive
argument:
powershell -NoProfile -NonInteractive -Command "Uninstall-Module X"
I have yet to find such case, but if it still doesn't help, one may use (Get-InstalledModule -Name X).InstalledLocation
to find where the module got installed, and remove it by other means (last resort). If another / older version of the module was bundled with PowerShell, it's best to avoid manual removal not to break it.
Workarounds
- Maybe in this case uninstall is not necessary, and it's possible to install your module, keep it, and update it with
Update-InstalledModule
when needed? - Many modules can get imported without installation.
Import-Module
with the path of .psd1 file is likely to work. Still, it doesn't makeRemove-Module
work 100%. - If security is a concern, one can install the module only for the service user with
Install-Module -Scope CurrentUser
, and/or restrict PowerShell usage withSet-ExecutionPolicy
, which can be run with-Scope
argument too.
In my case, I solved this this way:
- Close PowerShell.
- Really, close PowerShell. Open up Task Manager and find any background instances of PowerShell, as in either or both powershell.exe / pwsh.exe.
- Delete the unwanted module folders from C:\Users\${USER}\Documents\PowerShell\Modules