Last active
June 11, 2021 08:48
-
-
Save nichollsc81/7909c94060d391c644922dfed498e0a9 to your computer and use it in GitHub Desktop.
Removes all previous versions of an installed module
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 Remove-ModulePreviousVersion { | |
| <# | |
| .SYNOPSIS | |
| Removes all previous versions of given module. | |
| .DESCRIPTION | |
| Long description | |
| .EXAMPLE | |
| PS C:\> $m = 'oh-my-posh' | |
| PS C:\> Remove-ModulePreviousVersion -ModuleName $m -Verbose -WhatIf | |
| Removes all previous versions of given module oh-mu-posh | |
| .INPUTS | |
| [String] | |
| .NOTES | |
| Supports Verbose. Support WhatIf. | |
| #> | |
| [cmdletbinding(SupportsShouldProcess)] | |
| param( | |
| [Parameter(ValueFromPipeline = $true,Position=0)] | |
| [string] $ModuleName | |
| ) | |
| begin | |
| { | |
| # set common parameters | |
| $ErrorActionPreference = 'Stop' | |
| $commonParams = @{} | |
| if($WhatIfPreference.IsPresent) {$commonParams.Add('WhatIf', $true)} | |
| if($VerbosePreference.IsPresent) {$commonParams.Add('Verbose', $true)} | |
| # ensure user is admin | |
| $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) | |
| [bool] $Admin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) | |
| if(-not ($Admin)) { | |
| Write-Warning "User not admin. Please elevate shell." | |
| Break | |
| } | |
| # capture function name for logging | |
| $f = (Get-PSCallStack).Command[0] | |
| # get latest installed version of module | |
| Write-Verbose "[$f] Determining latest version of $ModuleName" | |
| $Latest = Get-InstalledModule $ModuleName -Verbose:$VerbosePreference | |
| } | |
| process | |
| { | |
| # determine previously installed versions, if any | |
| Write-Verbose "[$f] Determining installed versions of $ModuleName" | |
| $InstalledVersions = Get-InstalledModule $ModuleName -AllVersions -Verbose:$VerbosePreference | ? { | |
| $_.Version -ne $Latest.Version | |
| } | |
| } | |
| end | |
| { | |
| # if older versions, remove | |
| if ($InstalledVersions) | |
| { | |
| $InstalledVersions | % { | |
| Write-Verbose "[$f] Removing version $($_.Version) of $($_.Name)" | |
| $paramHash = @{ | |
| Name = $_.Name | |
| RequiredVersion = $_.Version | |
| } | |
| Uninstall-Module @paramHash -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference | |
| } | |
| } | |
| else | |
| { | |
| "[$f] No versions of $ModuleName module previously installed." | |
| } | |
| Write-Verbose "[$f] Function execution complete." | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment