Last active
July 21, 2020 23:13
-
-
Save pixelicous/a5fc4a1666d47839afe05204e330587d to your computer and use it in GitHub Desktop.
Uninstall modules with quick examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Uninstall-AllModules { | |
param( | |
[Parameter(Mandatory=$true)] | |
[string]$TargetModule, | |
[Parameter(Mandatory=$true)] | |
[string]$Version, | |
[switch]$Force, | |
[switch]$WhatIf | |
) | |
$AllModules = @() | |
'Creating list of dependencies...' | |
$target = Find-Module $TargetModule -RequiredVersion $version | |
$target.Dependencies | ForEach-Object { | |
if ($_.requiredVersion) { | |
$AllModules += New-Object -TypeName psobject -Property @{name=$_.name; version=$_.requiredVersion} | |
} | |
else { # Assume minimum version | |
# Minimum version actually reports the installed dependency | |
# which is used, not the actual "minimum dependency." Check to | |
# see if the requested version was installed as a dependency earlier. | |
$candidate = Get-InstalledModule $_.name -RequiredVersion $version | |
if ($candidate) { | |
$AllModules += New-Object -TypeName psobject -Property @{name=$_.name; version=$version} | |
} | |
else { | |
Write-Warning ("Could not find uninstall candidate for {0}:{1} - module may require manual uninstall" -f $_.name,$version) | |
} | |
} | |
} | |
$AllModules += New-Object -TypeName psobject -Property @{name=$TargetModule; version=$Version} | |
foreach ($module in $AllModules) { | |
Write-Host ('Uninstalling {0} version {1}...' -f $module.name,$module.version) | |
try { | |
Uninstall-Module -Name $module.name -RequiredVersion $module.version -Force:$Force -ErrorAction Stop -WhatIf:$WhatIf | |
} catch { | |
Write-Host ("`t" + $_.Exception.Message) | |
} | |
} | |
} | |
Uninstall-AllModules -TargetModule Az -Version 0.7.0 -Force | |
$versions = (Get-InstalledModule Az -AllVersions | Select-Object Version) | |
$versions[1..($versions.Length-1)] | foreach { Uninstall-AllModules -TargetModule Az -Version ($_.Version) -Force } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment