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.

So,

The following function has made this possible.

Function Uninstall-AllModules
{
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory = $true)]
[string]
$TargetModule,
[Parameter(Mandatory = $false)]
[string]
$Version,
[switch]
$Force
)

$AllModules = @()

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

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

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

Regards,
The Author – Blogabout.Cloud

Leave a Reply

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