How to uninstall PowerShell modules with dependencies within a script.

PowerShell module can sometimes become a nightmare if there are dependencies on other modules. I have been recently looking at my AzureADPreview which had one dependency for;

– Microsoft365DSC module

If you run the standard uninstall-module -name AzureADPreview you will receive an error stating the module cannot be uninstalled due to the dependency of the other module as shown below;

If you run install-module AzureADPreview you are likely to receive a duplicate install of the same module which will potential cause issues later down the line.


The following function has made this possible.

Function Uninstall-AllModules
param (
[Parameter(Mandatory = $true)]
[Parameter(Mandatory = $false)]

$AllModules = @()

‘Creating list of dependencies…’
$target = Find-Module $TargetModule
$target.Dependencies | ForEach-Object {
$AllModules += New-Object -TypeName psobject -Property @{ name = $}
$AllModules += New-Object -TypeName psobject -Property @{ name = $TargetModule}

$cnt = 1;
foreach ($module in $AllModules)
Write-Host (“[$cnt] – ” + ‘Uninstalling {0} version’ -f $;
if ($PSCmdlet.ShouldProcess($, ‘Uninstall’))
Uninstall-Module -Name $ -Force:$Force -ErrorAction Stop;
Write-Host (“`t” + $_.Exception.Message)

## – Example using -WhatIf parameter:
Uninstall-AllModules -TargetModule AzureAD -Force

The Author – Blogabout.Cloud

Leave a Reply

Your email address will not be published. Required fields are marked *