Post

Update PowerShell Modules

Updating Installed PowerShell Modules with a Script

Are you tired of manually updating your installed PowerShell modules? This script can help you automate the process. The script updates all installed modules to the latest production or pre-release version, depending on the AllowPrerelease switch. It also uninstalls any older versions of the modules.

The script includes two optional parameters: AllowPrerelease and ShowErrors. If AllowPrerelease is specified, the script updates the modules to the latest pre-release versions. Otherwise, it updates to the latest production versions. If ShowErrors is specified, the script shows specific PowerShell error messages when an error occurs during the module update process.

The script first checks for admin privileges and retrieves all installed modules. It then loops through the installed modules and updates them if a newer version is available. After updating the modules, the script retrieves the newest version number and removes any old versions. Finally, the script displays a list of updated modules.

Here’s an example of how to use the script to update all installed modules to the latest pre-release versions and show specific error messages when an error occurs:

Example

Here’s an example of how to use the script to update all installed modules to the latest production versions without showing specific error messages:

1
.\Update-ModuleVersions.ps1

And here’s an example of how to use the script to update all installed modules to the latest pre-release versions and show specific error messages when an error occurs:

1
.\Update-ModuleVersions.ps1 -AllowPrerelease -ShowErrors

Full script

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
<#
.SYNOPSIS
Update installed modules to the latest production or pre-release version.

.DESCRIPTION
This function updates all installed modules to the latest production or pre-release version (based on the AllowPrerelease switch).

.PARAMETER AllowPrerelease
If specified, updates to the latest pre-release versions; otherwise, updates to the latest production versions.

.PARAMETER ShowErrors
If specified, shows specific PowerShell error messages when an error occurs during the module update process.

.EXAMPLE
Update-ModuleVersions -AllowPrerelease -ShowErrors
# Updates all installed modules to the latest pre-release versions and shows specific error messages when an error occurs.

.EXAMPLE
Update-ModuleVersions
# Updates all installed modules to the latest production versions without showing specific error messages.
#>

function Update-ModuleVersions {
    [CmdletBinding()]
    param (
        [switch]$AllowPrerelease,
        [switch]$ShowErrors
    )

    # Check admin privileges
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
        Throw "This function requires administrator privileges."
    }

    # Get all installed modules
    Write-Host "Retrieving all installed modules ..." -ForegroundColor Green
    $CurrentModules = Get-InstalledModule | Select-Object Name, Version | Sort-Object Name

    if (-not $CurrentModules) {
        Write-Host "No modules found." -ForegroundColor Gray
        return
    }
    else {
        $ModulesCount = $CurrentModules.Count
        Write-Host "$ModulesCount modules found." -ForegroundColor Gray
    }

    # Show status of AllowPrerelease Switch
    if ($AllowPrerelease) {
        Write-Host "Updating installed modules to the latest PreRelease version ..." -ForegroundColor Green
    }
    else {
        Write-Host "Updating installed modules to the latest Production version ..." -ForegroundColor Green
    }

    # Loop through the installed modules and update them if a newer version is available
    $i = 0
    foreach ($Module in $CurrentModules) {
        $i++
        $Counter = "[{0,-$($ModulesCount.ToString().Length)}/{1,-$($ModulesCount.ToString().Length)}]" -f $i, $ModulesCount
        Write-Host ("{0} Checking for updated version of module {1} ..." -f $Counter, $Module.Name) -ForegroundColor Green
        try {
            Update-Module -Name $Module.Name -AllowPrerelease:$AllowPrerelease -AcceptLicense -Scope:AllUsers -Force -ErrorAction Stop
        }
        catch {
            $errorMessage = "Error updating module {0}!" -f $Module.Name
            if ($ShowErrors) {
                $errorMessage += " Error message: {0}" -f $_.Exception.Message
            }
            Write-Host $errorMessage -ForegroundColor Red
        }

        # Retrieve newest version number and remove old(er) version(s) if any
        $AllVersions = Get-InstalledModule -Name $Module.Name -AllVersions | Sort-Object PublishedDate -Descending
        $MostRecentVersion = $AllVersions[0].Version
        if ($AllVersions.Count -gt 1) {
            Foreach ($Version in $AllVersions) {
                if ($Version.Version -ne $MostRecentVersion) {
                    try {
                        Write-Host ("{0} Uninstalling previous version {1} of module {2} ..." -f (' ' * $Counter.Length), $Version.Version, $Module.Name) -ForegroundColor Gray
                        Uninstall-Module -Name $Module.Name -RequiredVersion $Version.Version -Force -ErrorAction Stop
                    }
                    catch {
                        $errorMessage = "Error uninstalling previous version {0} of module {1}!" -f $Version.Version, $Module.Name
                        if ($ShowErrors) {
                            $errorMessage += " Error message: {0}" -f $_.Exception.Message
                        }
                        Write-Warning $errorMessage
                    }
                }
            }
        }
    }

    # Get the new module versions for comparing them to the previous one if updated
    $NewModules = Get-InstalledModule | Select-Object Name, Version | Sort-Object Name
    if ($NewModules) {
        Write-Host "`nList of updated modules:" -ForegroundColor Green
        $NoUpdatesFound = $true
        foreach ($Module in $NewModules) {
            $CurrentVersion = $CurrentModules | Where-Object Name -EQ $Module.Name
            if ($CurrentVersion.Version -notlike $Module.Version) {
                $NoUpdatesFound = $false
                Write-Host ("- Updated module {0} from version {1} to {2}" -f $Module.Name, $CurrentVersion.Version, $Module.Version) -ForegroundColor Green
            }
        }

        if ($NoUpdatesFound) {
            Write-Host "No modules were updated." -ForegroundColor Gray
        }
    }
}
Update-ModuleVersions
This post is licensed under CC BY 4.0 by the author.

Trending Tags