With nowadays rapid development and release cycles it’s a good practice to regularly check whether you have the latest available module versions installed. Using native PowerShell cmdlets you would first list the module installed locally and then search for the latest module online.
When you have several modules installed, this becomes a laborious task. So I wrote a cmdlet that does all this work for me and you if you like.
The Update-PoshModule cmdlet can check for an individual module or multiple modules that start with the same prefix.
To check the local version of Pester and whether there is a newer version available online I simply run the following command
1 |
Update-PoshModule -ModulePrefix Pester -RemovePreviousVersions –whatif |
Note that I use the –whatif parameter, since I only want to check whether there is a newer version. Next we remove the –whatif parameter to run the update.
Now I’m interested what the status is of my Azure Resource Manager modules. Instead of an exact module name, I just enter the Module prefix “AzureRm”
1 |
Update-PoshModule -ModulePrefix AzureRM –WhatIf |
- The –Scope parameter let’s you define whether you want to install the module for AllUsers or just the CurrentUser.
- with the –RemovePreviousVersions parameter enabled the script tries to remove older versions provided the user has access
- The ReturnOutput parameter, best used in combination with –what if returns an object with all the local and remote module informatin.
Note that the Update-PoshModule cmdlet only looks for PowerShell modules installed in Allusers scope i.e. “C:\Program Files\WindowsPowerShell\Modules” and CurrentUserr i.e. “C:\Users\alexv\Documents\WindowsPowerShell”
When using the –RemovePreviousVersions option I recommend to first run the command with the –wahtif command so you’re sure about what gets removed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
function Update-PoshModule { <# .Synopsis Update-PSModule .DESCRIPTION The Update-PoshModule cmdlet checks whether a newwer PowerShell Module version is available and when found installs it. Optionally previous versions of the Module can be removed. Note that the Update-PoshModule cmdlet only looks for PowerShell modules installed in Allusers scope i.e. "C:\Program Files\WindowsPowerShell\Modules" and CurrentUserr i.e. "C:\Users\alexv\Documents\WindowsPowerShell" .PARAMETER Repository The name of the Repository if no value is provided the PSGallery repository is used. .PARAMETER ModulePrefix The prefix or full PowerShell Module Name .PARAMETER RemovePreviousVersions When specified all older versions of the Module are removed from the local system. .PARAMETER SkipPublisherCheck Allows the installation of unsigned modules .PARAMETER Scope Specifies the installation scope of the module. The acceptable values for this parameter are: AllUsers and CurrentUser. The AllUsers scope lets modules be installed in a location that is accessible to all users of the computer, that is, %systemdrive%:\ProgramFiles\WindowsPowerShell\Modules. The CurrentUser scope lets modules be installed only to $home\Documents\WindowsPowerShell\Modules, so that the module is available only to the current user. .PARAMETER ReturnOutput When specifid the cmdlet returns an object containing all the collected module information. .EXAMPLE Update-PoshModule -Repository PSGAllery -ModulePrefix Pester -SkipPublisherCheck -Scope CurrentUser The above command checks whether there is a new Module version available for Pester in the Public PowerShell Repository and installs it .EXMAPLE Update-PoshModule -ModulePrefix Pester -RemovePreviousVersions -SkipPublisherCheck -Scope CurrentUser The above command checks whether there is a new moduole version available for Pester, installs it and removes older local installed versions. .EXAMPLE $modulestatus = Update-PoshModule -ModulePrefix AzureRM.S -whatif -ReturnOutput $modulestatus The above command stores all the local and remote powershell modules into the $modulestatus variable. .NOTES v1, 17.12.2017, alex verboon #> [CmdletBinding(SupportsShouldProcess=$true)] Param ( # PowerShell Module Repository name [Parameter(Mandatory=$false)] [string]$Repository = "PSGAllery", # Prefix or entire PoweShell module name [Parameter(Mandatory=$true)] [string]$ModulePrefix, # When enabled, removes previous module versions [switch]$RemovePreviousVersions, # allow instalaltion of unsigned modules [switch]$SkipPublisherCheck, # Installation Scope [Parameter()] [validateset("CurrentUser","AllUsers")] [string] $Scope = "AllUsers", [switch]$ReturnOutput ) Begin { # handle SkipPublishercheck to install unsigned modules $ParamSkipPublisherCheck = @{ SkipPublisherCheck = if ($PSBoundParameters.SkipPublisherCheck -eq $true) { $true } else { $false }; } # define the scope to install modules. If ($PSBoundParameters["Scope"]) { $ScopeParam = $Scope Write-Verbose "Scope: $ScopeParam" } Else { $ScopeParam = "AllUsers" Write-Verbose "Scope: $ScopeParam" } # PowerShell Module locations for CurrentUser and AllUsers $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell" $script:MyDocumentsPSPath = Microsoft.PowerShell.Management\Join-Path -Path $HOME -ChildPath 'Documents\WindowsPowerShell' $script:ProgramFilesModulesPath = Microsoft.PowerShell.Management\Join-Path -Path $script:ProgramFilesPSPath -ChildPath "Modules" $script:MyDocumentsModulesPath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsPSPath -ChildPath "Modules" $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent() $prp=new-object System.Security.Principal.WindowsPrincipal($wid) $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator $script:IsRunningAsElevated = $prp.IsInRole($adm) if(-not ($script:IsRunningAsElevated -eq $true) -and ($Scope -ne "CurrentUser")) { # Throw an error when Install-Module is used as a non-admin user and '-Scope CurrentUser' is not specified Write-Error "You must run PowerShell in elevated mode when installing for AllUsers or use the -Scope CurrentUser parameter" Throw } Write-Verbose "Checking Repository: $Repository" $repcheck = Get-PSRepository -Name $Repository -ErrorAction SilentlyContinue if ($repcheck.name -eq "$Repository") { Write-Verbose "Reppsitory $Repository found" } Else { Write-Warning "Unable to find the PowerShell Repository $Repository" Throw } Write-Output "Searching for Modules: $($ModulePrefix)..." $currentmodulesAll = Get-Module -ListAvailable | Where-Object {$_.name -like "$ModulePrefix*"} | Sort-Object -Unique $currentmodules = $currentmodulesAll | Select-Object * | Where-Object {$_.Path -like "$script:MyDocumentsModulesPath*" -or $_.Path -like "$script:ProgramFilesModulesPath*"} If ($currentmodules.Count -ne 0) { $RepoCompare = @() ForEach ($mod in $currentmodules) { write-verbose "Searching for Module $($mod.name)" $latestrepo = Find-module -Name "$($mod.Name)" -Repository $Repository -ErrorAction Continue If ([string]::IsNullOrEmpty($latestrepo)) { Write-Warning "Module $($mod.name) not found" $prop = @{ "version" = "0" "name" = "unkonwn" } $latestrepo = New-Object -TypeName PSObject -Property $prop } $object = @{ LocalModuleType = $mod.ModuleType LocalVersion = $mod.version LocalName = $mod.Name LocalPath = $mod.path RemoteVersion = $latestrepo.version RemoteName = $latestrepo.Name PublishedDate = $latestrepo.publisheddate } $RepoCompare += (New-Object PSObject -Property $object) } } Else { Write-Warning "No PowerShell Modules found that match the Module Prefix or Name: $ModulePrefix" Break } } Process { ForEach ($entry in $RepoCompare) { Write-Output "----------------------------------------------------" write-output "PowerShell Module : $($entry.LocalName)" Write-Output "Installed version : $($entry.LocalVersion)" Write-Output "ModulePath : $($entry.localpath)" Write-Output "Latest version : $($entry.RemoteVersion)" Write-Output "PublishedDate : $($entry.PublishedDate)" If ([System.Version]"$($entry.LocalVersion)" -eq [system.version]"$($entry.RemoteVersion)" -eq $true) { Write-host "Latest version already installed" -ForegroundColor Green } Elseif ([System.Version]"$($entry.LocalVersion)" -gt [system.version]"$($entry.RemoteVersion)" -eq $true) { Write-host "A newer version is installed locally" -ForegroundColor Yellow } ElseIf ([System.Version]"$($entry.LocalVersion)" -lt [system.version]"$($entry.RemoteVersion)" -eq $true) { Write-host "A newer version is available" -ForegroundColor Magenta If ($PScmdlet.ShouldProcess("Installing latest version of PowerShell Module: $($entry.LocalName)")) { Try{ Write-output "Installing latest version" Find-Module "$($entry.LocalName)" -Repository $Repository | Install-Module -Force @ParamSkipPublisherCheck -Scope "$ScopeParam" } Catch{ Write-Warning "Unable to install latest version of PowerShell Module $($entry.LocalName)" Break } } } #} # ----------------------------------------------------------------------------------------- # # Remove Previous versions # ----------------------------------------------------------------------------------------- # If ($PSBoundParameters["RemovePreviousVersions"]) { if ($PSBoundParameters['whatif']) { $LatestVersion = $entry.remoteversion } Else { $LatestVersion = ((Get-Module -Name "$($entry.LocalName)" -ListAvailable | Sort-Object $_.version)[0]).Version } Write-Verbose "Most recent local version: $($LatestVersion)" $allversions = Get-Module -Name "$($entry.LocalName)" -ListAvailable | Where-Object {$_.Path -like "$script:MyDocumentsModulesPath*" -or $_.Path -like "$script:ProgramFilesModulesPath*"} ForEach ($version in $allversions) { If ($version.Version -ne $LatestVersion) { If ($PScmdlet.ShouldProcess("Removing lersion $($version.version) of PowerShell Module: $($entry.LocalName) from $($version.path)" )) { Try{ $ModulePsd = $version.Path $ModulePath = Split-Path $version.Path -Parent Write-Output "Removing Module $ModulePath" Remove-Module -FullyQualifiedName "$ModulePsd" -Force -ErrorAction SilentlyContinue Write-Output "Deleting Module Folder: $ModulePath" Remove-item -Path $ModulePath -Recurse -Force } Catch { Write-Warning "Unable to remove PowerShell Module "$($entry.LocalName)" version "$($version.version)"" } } } } } # ----------------------------------------------------------------------------------------- # } } End { If ($PSBoundParameters["ReturnOutput"]) {$RepoCompare} } } |
And as always, feedback is welcome.