Private/Test/Test-IsLatestVersion.ps1
|
function Test-IsLatestVersion { <# .SYNOPSIS Checks if the currently loaded module is the latest version available on the PowerShell Gallery. .DESCRIPTION This function compares the version of a module currently loaded in the session against the latest version available on the PowerShell Gallery. It returns true if the running version is up-to-date or newer (such as a pre-release version), and false if an update is available. .PARAMETER Name The name of the module to check. .INPUTS System.String You can pipe a module name to this function. .OUTPUTS System.Boolean Returns $true if the running version is greater than or equal to the gallery version. Returns $false if a newer version is available on the gallery. .EXAMPLE Test-IsLatestVersion -Name 'Locksmith2' Returns $true if running the latest version of Locksmith2, $false if an update is available. .EXAMPLE Test-IsLatestVersion -Name 'Pester' Checks if the loaded Pester module is the latest version available. .EXAMPLE if (-not (Test-IsLatestVersion -Name 'Locksmith2')) { Write-Host "A newer version of Locksmith 2 is available. Run 'Update-Module Locksmith2' to update." } Checks for updates and displays a message if one is available. .EXAMPLE 'Pester', 'PSScriptAnalyzer' | Test-IsLatestVersion Checks if multiple modules are up-to-date via pipeline input. .LINK https://www.powershellgallery.com/packages/Locksmith2 #> [CmdletBinding()] [OutputType([bool])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string]$Name ) #requires -Version 5.1 process { # Get the version of the module currently loaded in this session Write-Verbose "Checking if this is the latest version of $Name." $loadedModule = Get-Module -Name $Name if (-not $loadedModule) { $errorRecord = [System.Management.Automation.ErrorRecord]::new( [System.Exception]::new("$Name module is not currently loaded in this session."), 'ModuleNotLoaded', [System.Management.Automation.ErrorCategory]::ObjectNotFound, $Name ) $PSCmdlet.WriteError($errorRecord) return $false } $runningVersion = $loadedModule.Version Write-Verbose "Running version: $runningVersion" # Query the PowerShell Gallery for the latest published version try { $galleryVersion = [version](Find-Module -Name $Name -ErrorAction Stop).Version Write-Verbose "Gallery version: $galleryVersion" } catch { # If we can't reach the gallery, warn the user and return true to avoid blocking execution Write-Verbose "Gallery version: unknown. Error: $_" Write-Warning -Message "Could not check your trusted galleries for latest version of $Name." return $true } # Compare versions and return true if we're running the latest (or newer) ($runningVersion -ge $galleryVersion) } } |