How to Remove a PowerShell Module

Illustration showing how to remove a PowerShell module: open elevated PowerShell, run Uninstall-Module <ModuleName>, confirm removal, verify with Get-Module -ListAvailable. Now OK.

How to Remove a PowerShell Module

Understanding the Critical Need for PowerShell Module Management

PowerShell modules are the building blocks of automation and system administration in modern Windows environments, but they can quickly accumulate and create conflicts, consume unnecessary resources, or simply become outdated. Whether you're a system administrator managing multiple servers or a developer working on complex automation scripts, knowing how to properly remove PowerShell modules is essential for maintaining a clean, efficient, and secure working environment. Unmanaged modules can lead to version conflicts, unexpected behavior in scripts, and even security vulnerabilities when outdated modules remain installed with known exploits.

Removing a PowerShell module involves more than just deleting files from a directory. It requires understanding the module scope, dependencies, and the proper commands to ensure complete removal without breaking existing scripts or system functionality. PowerShell provides several built-in cmdlets and methods for module removal, each serving different purposes depending on whether you want to temporarily unload a module from memory or permanently remove it from your system.

Throughout this comprehensive guide, you'll discover multiple approaches to removing PowerShell modules, from simple one-line commands to advanced techniques for handling stubborn or protected modules. You'll learn how to identify which modules are installed, determine their locations, understand the differences between user and system-level modules, and execute safe removal procedures that won't compromise your system's stability. We'll also explore common troubleshooting scenarios and best practices that will help you maintain a clean PowerShell environment.

Identifying Installed PowerShell Modules

Before removing any module, you need to understand what's currently installed on your system. PowerShell stores modules in multiple locations depending on their scope, and identifying the correct module location is crucial for successful removal. The Get-Module cmdlet serves as your primary tool for discovering both loaded and available modules.

To view all currently loaded modules in your PowerShell session, simply execute Get-Module without any parameters. This displays modules that are actively imported and available for use in your current session. However, this only shows a fraction of what's actually installed on your system. To see all available modules, including those not currently loaded, use Get-Module -ListAvailable. This command scans all module paths defined in your PowerShell environment and returns a comprehensive list.

"Understanding module scope and location is the foundation of proper module management. Never attempt removal without first confirming the exact module path and version."

For more detailed information about a specific module, including its version, installation path, and exported commands, use Get-Module -Name ModuleName -ListAvailable | Format-List. This expanded view provides critical information such as:

  • ModuleBase: The physical directory where the module files are stored
  • Version: The installed version number, crucial when multiple versions exist
  • ExportedCommands: All cmdlets, functions, and aliases provided by the module
  • ModuleType: Whether it's a script, binary, or manifest module
  • Author and CompanyName: Source information for the module

Module Installation Scopes and Locations

PowerShell modules can be installed in different scopes, which determines their availability and the permissions required for removal. Understanding these scopes is essential for choosing the correct removal method.

Scope Installation Path Availability Removal Permissions
CurrentUser $HOME\Documents\PowerShell\Modules Only for the current user account Standard user permissions
AllUsers C:\Program Files\PowerShell\Modules All users on the system Administrator privileges required
System C:\Windows\System32\WindowsPowerShell\v1.0\Modules System-level, built-in modules Administrator privileges, protected by Windows

To view all module paths that PowerShell searches, examine the PSModulePath environment variable using $env:PSModulePath -split ';'. This reveals every directory where PowerShell looks for modules, which is particularly useful when troubleshooting module loading issues or tracking down unexpected module versions.

Removing Modules from Memory

The simplest form of module removal is unloading it from your current PowerShell session without deleting any files from disk. This temporary removal is useful when you need to reload a module with updated code, resolve conflicts between loaded modules, or simply free up memory in long-running sessions.

The Remove-Module cmdlet handles this task efficiently. To remove a single module from memory, use Remove-Module -Name ModuleName. This command unloads the module and all its exported commands from your current session, but the module files remain on disk and can be reimported at any time with Import-Module.

When working with modules that have dependencies or are used by other loaded modules, you might encounter errors during removal. The -Force parameter overrides these protections: Remove-Module -Name ModuleName -Force. Use this parameter cautiously, as forcing removal of a module that other components depend on can cause unexpected behavior in your session.

"Removing a module from memory is non-destructive and reversible. It's the safest first step when troubleshooting module-related issues."

Removing Multiple Modules Simultaneously

When you need to clean up multiple modules at once, PowerShell's pipeline capabilities become invaluable. You can combine Get-Module with Remove-Module to remove all loaded modules matching specific criteria.

To remove all modules with names starting with a specific prefix: Get-Module -Name PrefixName* | Remove-Module. This pattern-matching approach is particularly useful when working with module families that share a common naming convention, such as Azure modules (Az.*) or Exchange modules (Exchange*).

For removing all non-essential modules from your session while preserving core PowerShell functionality, you can filter by module type or source. For example, to remove all script modules while keeping binary modules: Get-Module | Where-Object {$_.ModuleType -eq 'Script'} | Remove-Module.

Permanently Uninstalling PowerShell Modules

Permanent module removal requires deleting the module files from disk, which frees up storage space and prevents the module from being loaded in future sessions. The method you use depends on how the module was originally installed.

Using Uninstall-Module for PowerShellGet Modules

For modules installed through PowerShellGet (using Install-Module), the Uninstall-Module cmdlet provides the cleanest removal method. This cmdlet understands module dependencies, version management, and proper cleanup procedures.

The basic syntax is straightforward: Uninstall-Module -Name ModuleName. This removes the latest version of the specified module from the CurrentUser scope. If the module was installed in the AllUsers scope, you'll need to run PowerShell as an administrator.

When multiple versions of a module are installed, Uninstall-Module only removes the newest version by default. To remove a specific version, specify it explicitly: Uninstall-Module -Name ModuleName -RequiredVersion 1.2.3. To remove all versions at once, use the -AllVersions parameter: Uninstall-Module -Name ModuleName -AllVersions.

"Always verify module dependencies before uninstalling. Removing a module that other modules depend on can break your PowerShell environment."

Checking Dependencies Before Removal

Before uninstalling any module, especially system-wide installations, check if other modules depend on it. Use Get-InstalledModule | Where-Object {$_.Dependencies -contains 'ModuleName'} to identify dependent modules. Removing a module with active dependencies will cause those dependent modules to fail when they attempt to load required functionality.

Some modules include a RequiredModules property that lists their dependencies. Examine this with (Get-Module -Name ModuleName -ListAvailable).RequiredModules to understand the module's relationship with other components before proceeding with removal.

Manual Module Deletion

When a module wasn't installed through PowerShellGet, or when Uninstall-Module fails, manual deletion becomes necessary. This approach requires careful attention to detail and proper permissions.

First, identify the module's exact location using Get-Module -Name ModuleName -ListAvailable | Select-Object -ExpandProperty ModuleBase. This returns the full path to the module's directory. Before deleting anything, ensure the module isn't currently loaded by running Remove-Module -Name ModuleName -ErrorAction SilentlyContinue.

To manually delete the module directory and all its contents, use Remove-Item -Path "C:\Path\To\Module" -Recurse -Force. The -Recurse parameter ensures all subdirectories and files are deleted, while -Force removes read-only files. Exercise extreme caution with this command, as there's no undo option once files are deleted.

Removal Method Best Used For Permissions Required Reversible
Remove-Module Temporary removal from session None (session-level) Yes (reimport anytime)
Uninstall-Module PowerShellGet installed modules Depends on scope Yes (reinstall from repository)
Manual deletion Manually installed or stubborn modules Depends on location No (unless backed up)

Handling Protected and System Modules

Windows includes several protected PowerShell modules that are integral to system functionality. These modules often resist standard removal methods and require special handling. Attempting to remove certain system modules can compromise Windows functionality or violate system integrity protection.

Modules located in C:\Windows\System32\WindowsPowerShell\v1.0\Modules are typically protected by Windows Resource Protection. Even with administrator privileges, you may encounter "Access Denied" errors when attempting to delete these modules. This protection exists for good reason – these modules are often required by Windows services and system processes.

"System modules are protected for your system's safety. If you must remove one, ensure you have a complete system backup and understand the potential consequences."

If you absolutely must remove a protected module, you'll need to take ownership of the files and modify their permissions. This process involves using takeown and icacls commands, but should only be performed when absolutely necessary and with full understanding of the implications. A safer alternative is to modify the PSModulePath environment variable to exclude the directory containing the problematic module, effectively hiding it from PowerShell without deleting system files.

Removing Modules Across Multiple Versions

PowerShell supports side-by-side installation of multiple module versions, which is beneficial for compatibility but can create confusion during removal. Each version occupies its own subdirectory within the module's folder, and PowerShell automatically loads the newest version unless specified otherwise.

To view all installed versions of a specific module, use Get-InstalledModule -Name ModuleName -AllVersions. This displays every version currently on your system, along with installation dates and repository sources.

When removing specific versions while keeping others, precision is essential. Use Uninstall-Module -Name ModuleName -RequiredVersion 2.1.0 to target an exact version. This is particularly important in production environments where scripts may depend on specific module versions.

Version Cleanup Strategy

A systematic approach to version cleanup prevents accidental removal of required versions:

  • 🔍 Audit current usage: Check all scripts and automation for hard-coded version requirements
  • 📊 Identify the newest stable version: Determine which version should remain as the default
  • 🗑️ Remove oldest versions first: Start with the most outdated versions and work forward
  • Test after each removal: Verify that dependent scripts still function correctly
  • 📝 Document the cleanup: Maintain records of which versions were removed and when

To remove all versions except the newest, use this approach: First, get all versions with $versions = Get-InstalledModule -Name ModuleName -AllVersions, then remove all but the latest with $versions | Where-Object {$_.Version -ne ($versions | Measure-Object -Property Version -Maximum).Maximum} | Uninstall-Module.

Troubleshooting Common Removal Issues

Module removal doesn't always proceed smoothly. Understanding common issues and their solutions helps you handle unexpected situations effectively.

Module In Use Errors

When attempting to remove a module that's currently loaded or being used by another process, you'll encounter errors indicating the module is in use. The solution involves first removing the module from memory with Remove-Module -Name ModuleName -Force, closing any other PowerShell sessions that might have the module loaded, and then attempting the uninstall again.

In some cases, a module might be loaded by a background service or scheduled task. Use Get-Process -Name pwsh,powershell | Select-Object Id,Path to identify all PowerShell processes, then terminate non-essential ones before attempting removal.

Permission Denied Errors

Access denied errors typically indicate insufficient permissions for the module's installation scope. Modules in the AllUsers scope require administrator privileges. Right-click PowerShell and select "Run as Administrator," then retry the removal command.

"Permission issues are the most common obstacle in module removal. Always verify your execution context matches the module's installation scope."

For persistent permission issues, check the module directory's security settings using Get-Acl -Path "C:\Path\To\Module" | Format-List. This reveals the current access control list and helps identify permission problems.

Incomplete Removal

Sometimes modules appear removed but leave behind residual files or registry entries. After uninstalling, verify complete removal by checking both the module path and running Get-Module -Name ModuleName -ListAvailable. If remnants remain, manually inspect the module directories and remove leftover files.

Certain modules create configuration files in user profile directories or program data folders. These locations vary by module but commonly include $HOME\.config, $HOME\AppData\Local, or C:\ProgramData. Consult the module's documentation for specific cleanup locations.

Best Practices for Module Removal

Implementing systematic practices for module removal minimizes risks and ensures maintainable PowerShell environments across your infrastructure.

Pre-Removal Verification

Before removing any module, especially in production environments, perform thorough verification. Document the module's current version, installation date, and scope. Export a list of all module commands with Get-Command -Module ModuleName | Export-Csv -Path "ModuleName_Commands.csv" for reference. Search your script repositories for any dependencies using Get-ChildItem -Path C:\Scripts -Recurse -Include *.ps1 | Select-String -Pattern "ModuleName".

Create a system restore point or backup before removing system-level modules. On Windows, use Checkpoint-Computer -Description "Before removing ModuleName" -RestorePointType "MODIFY_SETTINGS" to create a recovery point.

Testing in Non-Production Environments

Never test module removal procedures directly in production. Maintain a development or testing environment that mirrors your production configuration. Remove the module in the test environment first, then monitor for any unexpected behavior or broken dependencies over several days before proceeding with production removal.

"The time invested in proper testing always pays dividends. A broken production environment costs far more than a few hours of careful validation."

Documentation and Change Management

Maintain detailed records of all module changes, including removals. Document the removal date, reason, who performed the action, and any observed impacts. This documentation proves invaluable when troubleshooting future issues or conducting security audits.

For enterprise environments, integrate module removal into your change management process. Require approval for removing shared modules, schedule removals during maintenance windows, and communicate changes to all stakeholders who might be affected.

Alternative Approaches: Disabling Without Removing

Sometimes complete removal isn't the best solution. Disabling a module temporarily or preventing its automatic loading offers a middle ground that preserves the option to re-enable functionality without reinstallation.

Modifying PSModulePath

The PSModulePath environment variable controls where PowerShell searches for modules. By removing a directory from this path, you effectively hide all modules in that location without deleting files. To temporarily modify the path for your current session, use $env:PSModulePath = ($env:PSModulePath -split ';' | Where-Object {$_ -notlike '*PathToExclude*'}) -join ';'.

For permanent changes, modify the system or user environment variables through Windows settings or use [Environment]::SetEnvironmentVariable("PSModulePath", $newPath, "User") for user-level changes or "Machine" for system-level changes (requires administrator privileges).

Creating Module Blocklists

PowerShell 7 and later support module analysis and security features that can prevent specific modules from loading. While not a removal method per se, this approach prevents module usage without deletion. Configure module allowlists and blocklists through PowerShell security policies to control which modules can be imported in your environment.

Cleaning Up Module Dependencies

Modules often install additional dependencies that aren't automatically removed when the parent module is uninstalled. These orphaned dependencies consume disk space and can cause confusion in module management.

To identify potentially orphaned modules, first get a list of all installed modules: $allModules = Get-InstalledModule. Then, for each module, check if it's listed as a dependency for any other module. Modules that appear in no dependency lists and weren't explicitly installed by you are candidates for removal.

Create a script to automate dependency checking:

$installed = Get-InstalledModule
$dependencies = $installed | ForEach-Object { $_.Dependencies } | Select-Object -Unique
$orphans = $installed | Where-Object { $_.Name -notin $dependencies.Name }
$orphans | Format-Table Name, Version, InstalledDate

This identifies modules that aren't dependencies of any other installed module, though you should still verify each one before removal to ensure it wasn't intentionally installed for direct use.

Security Considerations in Module Removal

Module removal has security implications that extend beyond simple file deletion. Outdated modules may contain known vulnerabilities, but removing certain security-related modules can also create gaps in your defense posture.

Before removing any module, check for security advisories related to it. Search the PowerShell Gallery security advisories and the module's repository for any reported vulnerabilities. If a module is being removed due to security concerns, ensure no scripts or automation still reference it, as failed imports might cause security checks to be bypassed.

When removing modules that handle credentials or authentication, verify that no cached credentials or tokens remain in user profiles or credential managers. Some modules store sensitive data in locations that aren't cleaned during standard uninstallation.

Automating Module Cleanup

For environments with multiple systems or frequent module changes, automation streamlines the cleanup process and ensures consistency across your infrastructure.

Creating a Module Cleanup Script

Develop a standardized script that handles common cleanup scenarios. This script should include parameters for module names, version specifications, and scope, along with safety checks to prevent accidental removal of critical modules.

A basic cleanup script framework includes pre-removal validation, backup creation, the actual removal process, post-removal verification, and logging. Implement error handling to gracefully manage failures and provide detailed output for troubleshooting.

Scheduled Maintenance Tasks

Configure scheduled tasks to perform regular module maintenance, such as removing old versions while keeping the latest two releases, or cleaning up modules that haven't been used in a specified timeframe. Use PowerShell's job scheduling capabilities or Windows Task Scheduler to run these maintenance scripts during off-peak hours.

Monitor module usage by logging Import-Module commands in your PowerShell profiles or through transcript logging. This data helps identify modules that are no longer actively used and are safe candidates for removal.

Recovery Options After Removal

Even with careful planning, you might need to recover a removed module. Understanding recovery options provides a safety net for module management operations.

Reinstalling from Repositories

Modules originally installed from the PowerShell Gallery or other repositories can be easily reinstalled using Install-Module -Name ModuleName. To reinstall a specific version, add the -RequiredVersion parameter. For modules from private repositories, ensure the repository is still registered in your PowerShell configuration with Get-PSRepository.

If a module has been deprecated or removed from its original repository, check for archived versions or alternative sources. Some organizations maintain internal module repositories that retain historical versions for exactly this purpose.

Restoring from Backups

If you created backups before removal, restoration is straightforward. Copy the module directory back to its original location in the appropriate PSModulePath directory. After restoring files, verify the module loads correctly with Import-Module -Name ModuleName and test its functionality.

For system restore points, use the Windows System Restore utility to roll back to a point before the module was removed. This approach restores not just the module but all system changes made since the restore point was created.

Frequently Asked Questions
How do I remove a PowerShell module that won't uninstall normally?

If Uninstall-Module fails, first ensure you're running PowerShell with appropriate permissions for the module's scope. Try removing the module from memory with Remove-Module -Name ModuleName -Force, close all other PowerShell sessions, and attempt uninstallation again. If this still fails, locate the module directory using Get-Module -Name ModuleName -ListAvailable | Select-Object ModuleBase and manually delete the directory using Remove-Item -Path "ModulePath" -Recurse -Force. Always verify the module is no longer in use by other processes before manual deletion.

What's the difference between Remove-Module and Uninstall-Module?

Remove-Module unloads a module from your current PowerShell session's memory but doesn't delete any files from disk. The module remains installed and can be reimported at any time. Uninstall-Module permanently deletes the module files from your system, removing it completely. Use Remove-Module for temporary removal during troubleshooting or when you need to reload a module, and Uninstall-Module when you want to permanently remove the module from your system.

Can I remove built-in Windows PowerShell modules?

While technically possible, removing built-in Windows modules is strongly discouraged as they're often required by Windows services and system processes. These modules are typically protected by Windows Resource Protection. If you must prevent a built-in module from loading, modify the PSModulePath environment variable to exclude the system modules directory rather than deleting the files. This approach hides the module from PowerShell without compromising system integrity or violating Windows protection mechanisms.

How do I remove all versions of a module except the latest?

Use Get-InstalledModule -Name ModuleName -AllVersions to list all versions, then pipe the results to filter out the newest version before uninstalling. The command Get-InstalledModule -Name ModuleName -AllVersions | Where-Object {$_.Version -ne (Get-InstalledModule -Name ModuleName).Version} | Uninstall-Module removes all versions except the latest. Always test this in a non-production environment first, as some scripts may depend on specific older versions.

What should I do if removing a module breaks my scripts?

First, identify which specific commands or features from the removed module your scripts depend on by searching your code for references to the module. If the module was removed unintentionally, reinstall it using Install-Module -Name ModuleName or restore from backup. If the removal was intentional, you'll need to either update your scripts to use alternative commands, install a replacement module that provides similar functionality, or refactor your code to eliminate the dependency. Always test scripts in a development environment after module changes before deploying to production.

SPONSORED

Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.