diff --git a/.github/workflows/Build Module.yml b/.github/workflows/Build Module.yml index 7c15cf76..cbb82b8a 100644 --- a/.github/workflows/Build Module.yml +++ b/.github/workflows/Build Module.yml @@ -10,6 +10,7 @@ on: - "src/PSPreworkout.build.ps1" - "src/PSPreworkout.Settings.ps1" - "src/PSScriptAnalyzerSettings.psd1" + - "Scripts/Update-AllTheThings*" - ".github/workflows/Build Module.yml" workflow_dispatch: @@ -57,3 +58,33 @@ jobs: name: zip-archive path: .\src\Archive if-no-files-found: warn + + compatibility-test: + name: 🧪 Update-AllTheThings (${{ matrix.name }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: + - name: Windows PowerShell 5.1 + os: windows-latest + executable: powershell.exe + - name: PowerShell 7 on Windows + os: windows-latest + executable: pwsh + - name: PowerShell 7 on Linux + os: ubuntu-latest + executable: pwsh + + steps: + - name: Harden the runner (Audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - name: ✅ Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: 🧪 Run focused compatibility tests + run: ${{ matrix.executable }} -NoLogo -NoProfile -File ./src/Tests/Invoke-UpdateAllTheThingsCompatibility.ps1 diff --git a/Scripts/Update-AllTheThings.ps1 b/Scripts/Update-AllTheThings.ps1 index f0992911..b2490f8a 100644 --- a/Scripts/Update-AllTheThings.ps1 +++ b/Scripts/Update-AllTheThings.ps1 @@ -1,6 +1,6 @@ <#PSScriptInfo -.DESCRIPTION A script to automatically update all PowerShell modules, PowerShell Help, and packages (apt, brew, Chocolatey, winget). -.VERSION 0.5.8 +.DESCRIPTION A script to automatically update all PowerShell modules, PowerShell Help, GitHub CLI extensions, GitHub Copilot CLI, and packages (apt, brew, Chocolatey, WinGet). +.VERSION 0.6.0 .GUID 3a1a1ec9-0ef6-4f84-963d-be1505dab6a8 .AUTHOR Sam Erde .COPYRIGHT (c) 2024 Sam Erde. All rights reserved. @@ -9,6 +9,804 @@ .PROJECTURI https://github.com/SamErde/PSPreWorkout/ .ICONURI #> + +function Test-PSPreworkoutCommand { + <# + .SYNOPSIS + Tests whether a command is available. + + .DESCRIPTION + Resolves a command without emitting an error and returns whether it was found. + + .PARAMETER Name + The name of the command to resolve. + + .OUTPUTS + System.Boolean + #> + + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$Name + ) + + return $null -ne (Get-Command -Name $Name -ErrorAction SilentlyContinue) +} + +function Get-PSPreworkoutPlatform { + <# + .SYNOPSIS + Gets the current operating-system platform. + + .DESCRIPTION + Returns a stable platform name across Windows PowerShell 5.1 and PowerShell 7. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param() + + if ($PSVersionTable.PSEdition -eq 'Desktop') { + return 'Windows' + } + if (Get-Variable -Name IsWindows -ValueOnly -ErrorAction SilentlyContinue) { + return 'Windows' + } + + if (Get-Variable -Name IsLinux -ValueOnly -ErrorAction SilentlyContinue) { + return 'Linux' + } + + if (Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue) { + return 'macOS' + } + + return 'Unknown' +} + +function Write-UpdateAllTheThingsProgress { + <# + .SYNOPSIS + Writes progress for Update-AllTheThings. + + .DESCRIPTION + Centralizes the parent progress record used by Update-AllTheThings and its + private update helpers. + + .PARAMETER CurrentOperation + The operation currently being performed. + + .PARAMETER PercentComplete + The percentage of the overall update that is complete. + + .PARAMETER Completed + Completes and removes the progress record. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter()] + [ValidateNotNullOrEmpty()] + [string]$CurrentOperation, + + [Parameter()] + [ValidateRange(0, 100)] + [int]$PercentComplete = 0, + + [Parameter()] + [switch]$Completed + ) + + if ($Completed) { + Write-Progress -Id 0 -Activity 'Update Everything' -Completed + return + } + + $ProgressParameters = @{ + Id = 0 + Activity = 'Update Everything' + CurrentOperation = $CurrentOperation + Status = "Progress: $PercentComplete`% Complete" + PercentComplete = $PercentComplete + } + Write-Progress @ProgressParameters +} + +function Invoke-UpdateNativeCommand { + <# + .SYNOPSIS + Invokes a native update command and validates its exit code. + + .DESCRIPTION + Provides consistent invocation and explicit failure handling for native + package-manager commands. + + .PARAMETER Name + The native command to invoke. + + .PARAMETER ArgumentList + Arguments passed to the native command. + + .PARAMETER FailureMessage + Context included in the terminating error when the command fails. + + .PARAMETER Command + An invocation seam used by unit tests. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$Name, + + [Parameter()] + [AllowEmptyCollection()] + [string[]]$ArgumentList = @(), + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$FailureMessage, + + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + param($CommandName, $CommandArguments) + + & $CommandName @CommandArguments | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command $Name $ArgumentList + if ($ExitCode -ne 0) { + throw "$FailureMessage failed with exit code $ExitCode." + } +} + +function Get-CimOperatingSystemCaption { + <# + .SYNOPSIS + Gets the operating-system caption through CIM. + + .DESCRIPTION + Queries CIM_OperatingSystem and returns its caption. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Query = { + (Get-CimInstance -ClassName CIM_OperatingSystem -ErrorAction Stop).Caption + } + ) + + return & $Query +} + +function Get-WmiOperatingSystemCaption { + <# + .SYNOPSIS + Gets the operating-system caption through WMI. + + .DESCRIPTION + Queries Win32_OperatingSystem and returns its caption for Windows PowerShell + 5.1 environments where CimCmdlets are unavailable. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSAvoidUsingWMICmdlet', + '', + Justification = 'Get-WmiObject is required as a Windows PowerShell 5.1 fallback when CimCmdlets are unavailable.' + )] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Query = { + (Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop).Caption + } + ) + + return & $Query +} + +function Get-WindowsOperatingSystemCaption { + <# + .SYNOPSIS + Gets the Windows operating-system caption. + + .DESCRIPTION + Uses CIM when available and falls back to WMI for Windows PowerShell 5.1 + environments where the CimCmdlets module is unavailable. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param() + + if (Test-PSPreworkoutCommand -Name 'Get-CimInstance') { + try { + return Get-CimOperatingSystemCaption + } catch { + Write-Verbose 'Get-CimInstance failed while checking the Windows operating system caption.' + } + } + + if (Test-PSPreworkoutCommand -Name 'Get-WmiObject') { + try { + return Get-WmiOperatingSystemCaption + } catch { + Write-Verbose 'Get-WmiObject failed while checking the Windows operating system caption.' + } + } +} + +function Read-WinGetServerChoice { + <# + .SYNOPSIS + Prompts before updating packages on Windows Server. + + .DESCRIPTION + Shows a host choice prompt that defaults to declining WinGet package updates. + + .OUTPUTS + System.Int32 + #> + + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [object]$HostUserInterface = $Host.UI + ) + + $Options = [System.Management.Automation.Host.ChoiceDescription[]]@( + [System.Management.Automation.Host.ChoiceDescription]::new('&Yes', 'Continue with WinGet package updates.') + [System.Management.Automation.Host.ChoiceDescription]::new('&No', 'Skip WinGet package updates.') + ) + + return $HostUserInterface.PromptForChoice( + 'Windows Server OS Found', + "Do you want to run 'winget upgrade' on your server?", + $Options, + 1 + ) +} + +function Invoke-WinGetUpgrade { + <# + .SYNOPSIS + Upgrades all user-scoped WinGet packages. + + .DESCRIPTION + Invokes WinGet non-interactively and throws when WinGet reports a failure. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & winget upgrade --silent --scope user --accept-package-agreements --accept-source-agreements --all | + Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "WinGet package upgrade failed with exit code $ExitCode." + } +} + +function Invoke-GitHubCliExtensionUpgrade { + <# + .SYNOPSIS + Upgrades installed GitHub CLI extensions. + + .DESCRIPTION + Invokes the GitHub CLI extension upgrade command and throws when it fails. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & gh extension upgrade --all | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "GitHub CLI extension upgrade failed with exit code $ExitCode." + } +} + +function Invoke-GitHubCopilotCliUpdate { + <# + .SYNOPSIS + Updates the GitHub Copilot CLI. + + .DESCRIPTION + Invokes the GitHub Copilot CLI update command and throws when it fails. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & copilot update | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "GitHub Copilot CLI update failed with exit code $ExitCode." + } +} + +function Set-UpdateRepositoryTrust { + <# + .SYNOPSIS + Trusts supported PowerShell Gallery repositories. + + .DESCRIPTION + Configures PSGallery as trusted for the installed PowerShellGet and + PSResourceGet clients. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param() + + Write-Verbose 'Set the PowerShell Gallery as a trusted installation source.' + + if ( + (Test-PSPreworkoutCommand -Name 'Set-PSRepository') -and + $PSCmdlet.ShouldProcess('PSGallery', 'Set PowerShellGet repository as trusted') + ) { + Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted + } + + if ( + (Test-PSPreworkoutCommand -Name 'Set-PSResourceRepository') -and + $PSCmdlet.ShouldProcess('PSGallery', 'Set PSResourceGet repository as trusted') + ) { + Set-PSResourceRepository -Name 'PSGallery' -Trusted + } +} + +function Update-PowerShellArtifact { + <# + .SYNOPSIS + Updates installed PowerShell modules, scripts, and help. + + .DESCRIPTION + Handles PowerShell-native update operations and their progress reporting. + + .PARAMETER SkipModules + Skips installed module updates. + + .PARAMETER SkipScripts + Skips installed script updates. + + .PARAMETER SkipHelp + Skips PowerShell help updates. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$SkipModules, + + [Parameter()] + [switch]$SkipScripts, + + [Parameter()] + [switch]$SkipHelp + ) + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Getting Installed PowerShell Modules' -PercentComplete 1 + + if ($SkipModules) { + Write-Information '[1] Skipping PowerShell Modules' -InformationAction Continue + } elseif (-not (Test-PSPreworkoutCommand -Name 'Get-InstalledModule')) { + Write-Warning 'Get-InstalledModule was not found. Skipping PowerShell module updates.' + } else { + Write-Information '[1] Getting Installed PowerShell Modules' -InformationAction Continue + $Modules = @(Get-InstalledModule) + Write-Information "[2] Updating $($Modules.Count) PowerShell Modules" -InformationAction Continue + + $ModuleIndex = 0 + foreach ($Module in $Modules) { + ++$ModuleIndex + $ModulePercent = [math]::Ceiling(($ModuleIndex / $Modules.Count) * 100) + $OverallPercent = [math]::Ceiling(10 + (60 * ($ModulePercent / 100))) + + Write-UpdateAllTheThingsProgress -CurrentOperation "Updating PowerShell module $($Module.Name)" -PercentComplete $OverallPercent + Write-Progress -Id 1 -ParentId 0 -Activity 'Updating PowerShell Modules' ` + -CurrentOperation $Module.Name -Status "Progress: $ModulePercent`% Complete" ` + -PercentComplete $ModulePercent + + if ($Module.Version -match 'alpha|beta|prerelease|preview') { + Write-Information "`t`tSkipping $($Module.Name) because a prerelease version is currently installed." -InformationAction Continue + continue + } + + try { + if ($PSCmdlet.ShouldProcess($Module.Name, 'Update PowerShell module')) { + Update-Module -Name $Module.Name + } + } catch [Microsoft.PowerShell.Commands.WriteErrorException] { + Write-Warning "Unable to update PowerShell module '$($Module.Name)': $($_.Exception.Message)" + } + } + } + + Write-Progress -Id 1 -Activity 'Updating PowerShell Modules' -Completed + + if ($SkipScripts) { + Write-Information '[2] Skipping PowerShell Scripts' -InformationAction Continue + } elseif (-not (Test-PSPreworkoutCommand -Name 'Update-Script')) { + Write-Warning 'Update-Script was not found. Skipping PowerShell script updates.' + } else { + Write-Information '[2] Updating PowerShell Scripts' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('Installed PowerShell scripts', 'Update scripts')) { + Update-Script + } + } + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating PowerShell Help' -PercentComplete 70 + + if ($SkipHelp) { + Write-Information '[3] Skipping PowerShell Help' -InformationAction Continue + } else { + Write-Information '[3] Updating PowerShell Help' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('PowerShell help files', 'Update help')) { + if ((Get-Culture).LCID -eq 127) { + Update-Help -UICulture en-US -ErrorAction SilentlyContinue + } else { + Update-Help -ErrorAction SilentlyContinue + } + } + } +} + +function Update-WinGetPackage { + <# + .SYNOPSIS + Updates user-scoped WinGet packages. + + .DESCRIPTION + Applies Windows Server safeguards before invoking WinGet. + + .PARAMETER Skip + Skips WinGet package updates. + + .PARAMETER AcceptPrompts + Bypasses the additional Windows Server confirmation prompt. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$Skip, + + [Parameter()] + [switch]$AcceptPrompts + ) + + if ($Skip) { + Write-Information '[4] Skipping WinGet' -InformationAction Continue + return + } + + if (-not (Test-PSPreworkoutCommand -Name 'winget')) { + Write-Information '[4] WinGet was not found. Skipping WinGet update.' -InformationAction Continue + return + } + + $ShouldUpdate = $PSCmdlet.ShouldProcess('WinGet packages', 'Upgrade all user-scoped packages') + $SkipServerPrompt = $AcceptPrompts -or $WhatIfPreference -or ( + $PSBoundParameters.ContainsKey('Confirm') -and (-not $Confirm) + ) + $ShouldProcessHandlesConsent = ($PSBoundParameters.ContainsKey('Confirm') -and $Confirm) -or ( + ($ConfirmPreference -ne [System.Management.Automation.ConfirmImpact]::None) -and + (([System.Management.Automation.ConfirmImpact]$ConfirmPreference) -le [System.Management.Automation.ConfirmImpact]::Medium) + ) + $NeedServerPrompt = (-not $SkipServerPrompt) -and (-not $ShouldProcessHandlesConsent) + + if ($NeedServerPrompt) { + $WindowsOsCaption = Get-WindowsOperatingSystemCaption + if ([string]::IsNullOrWhiteSpace($WindowsOsCaption)) { + Write-Warning -Message 'Unable to determine the Windows operating system caption. Skipping WinGet updates as a safety precaution.' + return + } + + if ($ShouldUpdate -and ($WindowsOsCaption -match 'Server')) { + Write-Warning -Message 'This is a server and updates could affect production systems. Do you want to continue with updating packages?' + if ((Read-WinGetServerChoice) -ne 0) { + return + } + Write-Verbose 'Continuing with WinGet package updates.' + } + } + + if ($ShouldUpdate -or $WhatIfPreference) { + Write-Information '[4] Updating WinGet Packages' -InformationAction Continue + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating WinGet Packages' -PercentComplete 80 + } + + if ($ShouldUpdate) { + Invoke-WinGetUpgrade + } +} + +function Update-LinuxPackage { + <# + .SYNOPSIS + Updates packages with supported Linux package managers. + + .DESCRIPTION + Updates apt and dnf packages, using sudo only when the current process is + not elevated. + + .PARAMETER AcceptPrompts + Passes the non-interactive acceptance argument to package managers. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$AcceptPrompts + ) + + $AptAvailable = Test-PSPreworkoutCommand -Name 'apt' + $DnfAvailable = Test-PSPreworkoutCommand -Name 'dnf' + if ((-not $AptAvailable) -and (-not $DnfAvailable)) { + return + } + + $NeedsSudo = -not (Test-IsElevated) + + if ($AptAvailable) { + Write-Information '[5] Updating apt packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('apt packages', 'Update and upgrade packages')) { + $CommandName = if ($NeedsSudo) { 'sudo' } else { 'apt' } + $UpdateArguments = if ($NeedsSudo) { @('apt', 'update') } else { @('update') } + [string[]]$UpgradeArguments = if ($NeedsSudo) { @('apt', 'upgrade') } else { @('upgrade') } + if ($AcceptPrompts) { + $UpgradeArguments += '-y' + } + + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $UpdateArguments -FailureMessage 'apt package index update' + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $UpgradeArguments -FailureMessage 'apt package upgrade' + } + } + + if ($DnfAvailable) { + Write-Information '[5] Updating dnf packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('dnf packages', 'Update packages')) { + $CommandName = if ($NeedsSudo) { 'sudo' } else { 'dnf' } + [string[]]$Arguments = if ($NeedsSudo) { @('dnf', 'update') } else { @('update') } + if ($AcceptPrompts) { + $Arguments += '-y' + } + + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $Arguments -FailureMessage 'dnf package update' + } + } +} + +function Update-MacOSPackage { + <# + .SYNOPSIS + Updates supported macOS software. + + .DESCRIPTION + Lists macOS software updates and updates Homebrew packages when Homebrew is + installed. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param() + + if ($PSCmdlet.ShouldProcess('macOS software updates', 'List available updates')) { + Invoke-UpdateNativeCommand -Name 'softwareupdate' -ArgumentList '-l' -FailureMessage 'macOS software update query' + } + + if (Test-PSPreworkoutCommand -Name 'brew') { + Write-Information '[6] Updating brew packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('Homebrew packages', 'Update and upgrade packages')) { + Invoke-UpdateNativeCommand -Name 'brew' -ArgumentList 'update' -FailureMessage 'Homebrew update' + Invoke-UpdateNativeCommand -Name 'brew' -ArgumentList 'upgrade' -FailureMessage 'Homebrew upgrade' + } + } +} + +function Update-OptionalCli { + <# + .SYNOPSIS + Updates an optional command-line tool. + + .DESCRIPTION + Runs a supplied update command when its command-line tool is installed. + + .PARAMETER CommandName + The command used to detect whether the tool is installed. + + .PARAMETER DisplayName + The status text displayed to the user. + + .PARAMETER CurrentOperation + The operation shown in the progress record. + + .PARAMETER TargetName + The ShouldProcess target. + + .PARAMETER ActionName + The ShouldProcess action. + + .PARAMETER PercentComplete + The overall completion percentage. + + .PARAMETER UpdateCommand + The update operation to invoke. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$CommandName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$DisplayName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$CurrentOperation, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$TargetName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$ActionName, + + [Parameter(Mandatory)] + [ValidateRange(0, 100)] + [int]$PercentComplete, + + [Parameter(Mandatory)] + [ValidateNotNull()] + [scriptblock]$UpdateCommand + ) + + if (-not (Test-PSPreworkoutCommand -Name $CommandName)) { + Write-Verbose "$DisplayName was skipped because $CommandName was not found." + return + } + + Write-Information $DisplayName -InformationAction Continue + Write-UpdateAllTheThingsProgress -CurrentOperation $CurrentOperation -PercentComplete $PercentComplete + if ($PSCmdlet.ShouldProcess($TargetName, $ActionName)) { + & $UpdateCommand + } +} + +function Update-ChocolateyPackage { + <# + .SYNOPSIS + Updates Chocolatey and installed Chocolatey packages. + + .DESCRIPTION + Optionally configures Chocolatey features when elevated, then updates + Chocolatey and all installed packages. + + .PARAMETER Include + Enables Chocolatey package updates. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$Include + ) + + if ((-not $Include) -or (-not (Test-PSPreworkoutCommand -Name 'choco'))) { + Write-Information '[9] Skipping Chocolatey' -InformationAction Continue + return + } + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating Chocolatey Packages' -PercentComplete 98 + Write-Information '[9] Updating Chocolatey Packages' -InformationAction Continue + + if (Test-IsElevated) { + if ($PSCmdlet.ShouldProcess('Chocolatey features', 'Enable global confirmation and disable non-elevated warnings')) { + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList @( + 'feature', 'enable', '-n=allowGlobalConfirmation' + ) -FailureMessage 'Chocolatey global confirmation configuration' + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList @( + 'feature', 'disable', '--name=showNonElevatedWarnings' + ) -FailureMessage 'Chocolatey non-elevated warning configuration' + } + } else { + Write-Verbose "Run once as an administrator to disable Chocolatey's showNonElevatedWarnings." -Verbose + } + + if ($PSCmdlet.ShouldProcess('Chocolatey packages', 'Upgrade Chocolatey and all packages')) { + $UpgradeArguments = @('-y', '--limit-output', '--accept-license', '--no-color') + $SelfUpdateArguments = @('upgrade', 'chocolatey') + $UpgradeArguments + $PackageUpdateArguments = @('upgrade', 'all') + $UpgradeArguments + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList $SelfUpdateArguments -FailureMessage 'Chocolatey self-update' + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList $PackageUpdateArguments -FailureMessage 'Chocolatey package update' + } + + Write-Information ' ' -InformationAction Continue +} + function Test-IsElevated { <# .SYNOPSIS @@ -23,25 +821,93 @@ function Test-IsElevated { .OUTPUTS Boolean #> - [CmdletBinding(HelpUri = 'https://day3bits.com/PSPreworkout')] + [CmdletBinding(HelpUri = 'https://day3bits.com/PSPreworkout/Test-IsElevated')] [Alias('isadmin', 'isroot')] + [OutputType([bool])] param () + # The standalone Update-AllTheThings script does not include module telemetry. + if (Get-Command -Name Write-PSPreworkoutTelemetry -CommandType Function -ErrorAction SilentlyContinue) { + Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + } + if (($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows) { $CurrentUser = [Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent()) return $CurrentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } else { - # Must be Linux or OSX, so use the id util. Root has userid of 0. - return 0 -eq (id -u) + # Unix-like systems (Linux, macOS, etc.) + # Method 1: Try id command with error handling + try { + $userId = & id -u 2>$null + if ($LASTEXITCODE -eq 0 -and $null -ne $userId) { + return 0 -eq [int]$userId + } + } catch { + Write-Debug "id command failed: $($_.Exception.Message)" + } + + # Method 2: Check username via .NET + try { + if ([System.Environment]::UserName -eq 'root') { + return $true + } + } catch { + Write-Debug ".NET username check failed: $($_.Exception.Message)" + } + + # Method 3: Check for macOS admin group membership + try { + # Check if we're on macOS and if user is in admin or wheel groups + if ($IsMacOS -or (Get-Command 'sw_vers' -ErrorAction SilentlyContinue)) { + # Method 3a: Use groups command to check admin group membership + $groups = & groups 2>$null + if ($LASTEXITCODE -eq 0 -and $groups) { + $groupList = $groups -split '\s+' + if ($groupList -contains 'admin' -or $groupList -contains 'wheel') { + return $true + } + } + + # Method 3b: Use id command to check group IDs + $groupIds = & id -G 2>$null + if ($LASTEXITCODE -eq 0 -and $groupIds) { + $gidList = $groupIds -split '\s+' | ForEach-Object { [int]$_ } + if ($gidList -contains 80 -or $gidList -contains 0) { + # 80=admin, 0=wheel + return $true + } + } + } + } catch { + Write-Debug "macOS admin group check failed: $($_.Exception.Message)" + } + + # Method 4: Check effective user ID via /proc (Linux-specific) + try { + if (Test-Path '/proc/self/status') { + $statusContent = Get-Content '/proc/self/status' -ErrorAction SilentlyContinue + $uidLine = $statusContent | Where-Object { $_ -match '^Uid:' } + if ($uidLine -and $uidLine -match '\s+(\d+)\s+') { + return 0 -eq [int]$matches[1] + } + } + } catch { + Write-Debug "/proc status check failed: $($_.Exception.Message)" + } + + # All methods failed + Write-Warning 'Unable to determine elevation status on this Unix-like system. All detection methods failed.' + return $false } } + function Update-AllTheThings { <# .SYNOPSIS Update all the things! .DESCRIPTION - A script to automatically update all PowerShell modules, PowerShell Help, and packages (apt, brew, Chocolatey, winget). + A script to automatically update all PowerShell modules, PowerShell Help, GitHub CLI extensions, GitHub Copilot CLI, and packages (apt, brew, Chocolatey, WinGet). .PARAMETER SkipModules Skip the step that updates PowerShell modules. @@ -53,13 +919,13 @@ function Update-AllTheThings { Skip the step that updates PowerShell help. .PARAMETER SkipWinGet - Skip the step the updates WinGet packages. + Skip the step that updates WinGet packages. .PARAMETER IncludeChocolatey Include Chocolatey package updates. .PARAMETER AcceptPrompts - Automatically accept prompts to install updates in Linux (apt, dnf). + Automatically accept prompts to install updates in Linux (apt, dnf) and continue WinGet updates on Windows Server without showing the extra server confirmation prompt. .EXAMPLE Update-AllTheThings @@ -69,48 +935,54 @@ function Update-AllTheThings { .EXAMPLE Update-AllTheThings -AcceptPrompts - Updates all of the things and automatically accepts Linux package upgrade prompts. + Updates all of the things and automatically accepts Linux package upgrade prompts and the additional WinGet confirmation prompt on Windows Server. + + .NOTES + Author: Sam Erde + Version: 0.6.0 #> - [CmdletBinding(SupportsShouldProcess)] - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', 'Update-AllTheThings', Justification = 'This is what we do.')] + [CmdletBinding( + SupportsShouldProcess, + ConfirmImpact = 'Medium', + HelpUri = 'https://day3bits.com/PSPreworkout/Update-AllTheThings' + )] + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'This is what we do.')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive Use')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '', Justification = 'WhatIf and Confirm are forwarded to private helpers that call ShouldProcess.')] [Alias('uatt')] param ( # Skip the step that updates PowerShell modules [Parameter()] - [switch] - $SkipModules, + [switch]$SkipModules, # Skip the step that updates PowerShell scripts [Parameter()] - [switch] - $SkipScripts, + [switch]$SkipScripts, # Skip the step that updates PowerShell help [Parameter()] - [switch] - $SkipHelp, + [switch]$SkipHelp, # Skip the step that updates WinGet packages [Parameter()] - [switch] - $SkipWinGet, + [switch]$SkipWinGet, - # Skip the step that updates Chocolatey packages + # Include Chocolatey package updates [Parameter()] [Alias('SkipChoco')] - [switch] - $IncludeChocolatey, + [switch]$IncludeChocolatey, - # Automatically accept prompts to install updates in Linux + # Automatically accept prompts to install updates [Parameter()] - [switch] - $AcceptPrompts + [switch]$AcceptPrompts ) begin { - # Spacing to get host output from script, winget, and choco all below the progress bar. + if (Test-PSPreworkoutCommand -Name 'Write-PSPreworkoutTelemetry') { + Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + } + $Banner = @" __ __ __ __ ___ ____ / / / /__ ___/ /__ _/ /____ / _ | / / / @@ -120,287 +992,74 @@ function Update-AllTheThings { /_ __/ / ___ /_ __/ / (_)__ ___ ____ / / / _ \/ -_) / / / _ \/ / _ \/ _ `(_-< /_/ /_//_/\__/ /_/ /_//_/_/_//_/\_, /___/ - /___/ 0.5.9 + /___/ v0.6.0 "@ Write-Host $Banner - } # end begin block + } process { - Write-Verbose 'Set the PowerShell Gallery as a trusted installation source.' - Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted - if (Get-Command -Name Set-PSResourceRepository -ErrorAction SilentlyContinue) { - Set-PSResourceRepository -Name 'PSGallery' -Trusted - } - - #region UpdatePowerShell - - # ==================== Update PowerShell Modules ==================== - - # Update the outer progress bar - $PercentCompleteOuter = 1 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Getting Installed PowerShell Modules' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - if (-not $SkipModules) { - # Get all installed PowerShell modules - Write-Host '[1] Getting Installed PowerShell Modules' - $Modules = (Get-InstalledModule) - $ModuleCount = $Modules.Count - Write-Host "[2] Updating $ModuleCount PowerShell Modules" - } else { - Write-Host '[1] Skipping PowerShell Modules' - } - - # Estimate 10% progress so far and 70% at the next step - $PercentCompleteOuter_Modules = 10 - [int]$Module_i = 0 - - # Update all PowerShell modules - foreach ($module in $Modules) { - # Update the module loop counter and percent complete for both progress bars - ++$Module_i - [double]$PercentCompleteInner = [math]::ceiling( (($Module_i / $ModuleCount) * 100) ) - [double]$PercentCompleteOuter = [math]::ceiling( $PercentCompleteOuter_Modules + (60 * ($PercentCompleteInner / 100)) ) - - # Update the outer progress bar while updating modules - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - # Update the child progress bar while updating modules - $ProgressParam1 = @{ - Id = 1 - ParentId = 0 - Activity = 'Updating PowerShell Modules' - CurrentOperation = "$($module.Name)" - Status = "Progress: $PercentCompleteInner`% Complete" - PercentComplete = $PercentCompleteInner - } - Write-Progress @ProgressParam1 - - # Do not update prerelease modules - if ($module.Version -match 'alpha|beta|prerelease|preview') { - Write-Information "`t`tSkipping $($module.Name) because a prerelease version is currently installed." -InformationAction Continue - continue - } - - # Finally update the current module - try { - Update-Module $module.Name - } catch [Microsoft.PowerShell.Commands.WriteErrorException] { - # Add a catch for mismatched certificates between module versions. - Write-Verbose $_ + $CommonParameters = @{} + foreach ($CommonParameterName in 'WhatIf', 'Confirm') { + if ($PSBoundParameters.ContainsKey($CommonParameterName)) { + $CommonParameters[$CommonParameterName] = $PSBoundParameters[$CommonParameterName] } } - # ##### Add a section for installed scripts +++++ - if (-not $SkipScripts) { - Write-Host '[2] Updating PowerShell Scripts' - Update-Script - } else { - Write-Host '[2] Skipping PowerShell Scripts' - } - # ##### Add a section for installed scripts +++++ - - # Complete the child progress bar after updating modules - Write-Progress -Id 1 -Activity 'Updating PowerShell Modules' -Completed - + $Platform = Get-PSPreworkoutPlatform - # ==================== Update PowerShell Help ==================== + Set-UpdateRepositoryTrust @CommonParameters + Update-PowerShellArtifact -SkipModules:$SkipModules -SkipScripts:$SkipScripts -SkipHelp:$SkipHelp @CommonParameters - # Update the outer progress bar while updating help - $PercentCompleteOuter = 70 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating PowerShell Help' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - if (-not $SkipHelp) { - Write-Host '[3] Updating PowerShell Help' - # Fixes error with culture ID 127 (Invariant Country), which is not associated with any language - if ((Get-Culture).LCID -eq 127) { - Update-Help -UICulture en-US -ErrorAction SilentlyContinue - } else { - Update-Help -ErrorAction SilentlyContinue - } - } else { - Write-Host '[3] Skipping PowerShell Help' - } - #endregion UpdatePowerShell - - #region UpdateWinget - # >>> Create a section to check OS and client/server OS at the top of the script <<< # - if ($IsWindows -or ($PSVersionTable.PSVersion -le [version]'5.1')) { - - if ((Get-CimInstance -ClassName CIM_OperatingSystem).Caption -match 'Server') { - # If on Windows Server, prompt to continue before automatically updating packages. - Write-Warning -Message 'This is a server and updates could affect production systems. Do you want to continue with updating packages?' - - $Yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Description.' - $No = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'Description.' - $Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No) - - $Title = 'Windows Server OS Found' - $Message = "Do you want to run 'winget update' on your server?" - $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, 1) - switch ($Result) { - 0 { - continue - } - 1 { - $SkipWinGet = $true - } - } - } - - if (-not $SkipWinGet) { - # Update all winget packages - Write-Host '[4] Updating Winget Packages' - # Update the outer progress bar for winget section - $PercentCompleteOuter = 80 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating Winget Packages' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - if (Get-Command winget -ErrorAction SilentlyContinue) { - winget upgrade --silent --scope user --accept-package-agreements --accept-source-agreements --all - } else { - Write-Host '[4] WinGet was not found. Skipping WinGet update.' - } - } else { - Write-Host '[3] Skipping WinGet' - continue - } + if ($Platform -eq 'Windows') { + Update-WinGetPackage -Skip:$SkipWinGet -AcceptPrompts:$AcceptPrompts @CommonParameters } else { Write-Verbose '[4] Not Windows. Skipping WinGet.' } - #endregion UpdateWinget - - #region UpdateLinuxPackages - # Early testing. No progress bar yet. Need to check for admin, different distros, and different package managers. - if ($IsLinux) { - # Determine if we need sudo (not needed if already root) - $NeedsSudo = -not (Test-IsElevated) - - if (Get-Command apt -ErrorAction SilentlyContinue) { - Write-Host '[5] Updating apt packages.' - if ($NeedsSudo) { - & sudo apt update - if ($AcceptPrompts) { - & sudo apt upgrade -y - } else { - & sudo apt upgrade - } - } else { - & apt update - if ($AcceptPrompts) { - & apt upgrade -y - } else { - & apt upgrade - } - } - } - if (Get-Command dnf -ErrorAction SilentlyContinue) { - Write-Host '[5] Updating dnf packages.' - if ($NeedsSudo) { - if ($AcceptPrompts) { - & sudo dnf update -y - } else { - & sudo dnf update - } - } else { - if ($AcceptPrompts) { - & dnf update -y - } else { - & dnf update - } - } - } + + if ($Platform -eq 'Linux') { + Update-LinuxPackage -AcceptPrompts:$AcceptPrompts @CommonParameters } else { Write-Verbose '[5] Not Linux. Skipping section.' } - #endregion UpdateLinuxPackages - - #region UpdateMacOS - # Early testing. No progress bar yet. Need to check for admin and different package managers. - if ($IsMacOS) { - softwareupdate -l - if (Get-Command brew -ErrorAction SilentlyContinue) { - Write-Host '[6] Updating brew packages.' - brew update - brew upgrade - } + + if ($Platform -eq 'macOS') { + Update-MacOSPackage @CommonParameters } else { Write-Verbose '[6] Not macOS. Skipping section.' } - #endregion UpdateMacOS - - #region UpdateChocolatey - # Upgrade Chocolatey packages. Need to check for admin to avoid errors/warnings. - if ((Get-Command choco -ErrorAction SilentlyContinue) -and $IncludeChocolatey) { - # Update the outer progress bar - $PercentCompleteOuter = 90 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating Chocolatey Packages' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter + + $OptionalCliUpdates = @( + @{ + CommandName = 'gh' + DisplayName = '[7] Updating GitHub CLI Extensions' + CurrentOperation = 'Updating GitHub CLI Extensions' + TargetName = 'GitHub CLI extensions' + ActionName = 'Upgrade all installed extensions' + PercentComplete = 90 + UpdateCommand = { Invoke-GitHubCliExtensionUpgrade } } - Write-Progress @ProgressParamOuter - Write-Host '[7] Updating Chocolatey Packages' - # Add a function/parameter to run these two feature configuration options, which requires admin to set. - if (Test-IsElevated) { - # Oops, this depends on PSPreworkout being installed or that function otherwise being available. - choco feature enable -n=allowGlobalConfirmation - choco feature disable --name=showNonElevatedWarnings - } else { - Write-Verbose "Run once as an administrator to disable Chocolatey's showNonElevatedWarnings." -Verbose + @{ + CommandName = 'copilot' + DisplayName = '[8] Updating GitHub Copilot CLI' + CurrentOperation = 'Updating GitHub Copilot CLI' + TargetName = 'GitHub Copilot CLI' + ActionName = 'Update installed CLI' + PercentComplete = 95 + UpdateCommand = { Invoke-GitHubCopilotCliUpdate } } - choco upgrade chocolatey -y --limit-output --accept-license --no-color - choco upgrade all -y --limit-output --accept-license --no-color - # Padding to reset host before updating the progress bar. - Write-Host ' ' - } else { - Write-Host '[7] Skipping Chocolatey' + ) + + foreach ($CliUpdate in $OptionalCliUpdates) { + Update-OptionalCli @CliUpdate @CommonParameters } - #endregion UpdateChocolatey - } # end process block + Update-ChocolateyPackage -Include:$IncludeChocolatey @CommonParameters + } end { Write-Host 'Done.' - # Update the outer progress bar - $PercentCompleteOuter = 100 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Finished' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - # Complete the outer progress bar - Write-Progress -Id 0 -Activity 'Update Everything' -Completed + Write-UpdateAllTheThingsProgress -CurrentOperation 'Finished' -PercentComplete 100 + Write-UpdateAllTheThingsProgress -Completed } - } diff --git a/Scripts/Update-AllTheThings_Build.ps1 b/Scripts/Update-AllTheThings_Build.ps1 index b4623215..f724d2b9 100644 --- a/Scripts/Update-AllTheThings_Build.ps1 +++ b/Scripts/Update-AllTheThings_Build.ps1 @@ -1,3 +1,4 @@ +[CmdletBinding()] param ( # Type of version level update [Parameter(Position = 0)] @@ -13,66 +14,110 @@ param ( # Publish the script [Parameter()] [switch] - $Publish + $Publish, + + # Destination for the generated standalone script + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] + $OutputPath ) -# Detect if running as a script or copy/paste in shell ($PSScriptRoot vs $PWD). -if ($PSScriptRoot) { - $ScriptInfo = (Join-Path -Path $PSScriptRoot -ChildPath 'Update-AllTheThings_ScriptInfo.ps1') - $Path1 = $([System.IO.Path]::Combine($PSScriptRoot, '..', 'src', 'PSPreworkout', 'Public', 'Test-IsElevated.ps1')) - $Path2 = $([System.IO.Path]::Combine($PSScriptRoot, '..', 'src', 'PSPreworkout', 'Public', 'Update-AllTheThings.ps1')) +$ScriptsRoot = if ($PSScriptRoot) { + $PSScriptRoot } else { - $ScriptInfo = (Join-Path -Path $pwd -ChildPath 'Update-AllTheThings_ScriptInfo.ps1') - $Path1 = $([System.IO.Path]::Combine($PWD, '..', 'src', 'PSPreworkout', 'Public', 'Test-IsElevated.ps1')) - $Path2 = $([System.IO.Path]::Combine($PWD, '..', 'src', 'PSPreworkout', 'Public', 'Update-AllTheThings.ps1')) + $PWD.Path } -# Get the contents of the PSScriptInfo file and any scripts to merge. -$Content0 = Get-Content -Path $ScriptInfo -$Content1 = Get-Content -Path $Path1 -$Content2 = Get-Content -Path $Path2 +$RepositoryRoot = [System.IO.Path]::GetFullPath((Join-Path -Path $ScriptsRoot -ChildPath '..')) +$ModuleRoot = Join-Path -Path $RepositoryRoot -ChildPath 'src\PSPreworkout' +$ScriptInfoPath = Join-Path -Path $ScriptsRoot -ChildPath 'Update-AllTheThings_ScriptInfo.ps1' +$UpdateCommandPath = Join-Path -Path $ModuleRoot -ChildPath 'Public\Update-AllTheThings.ps1' + +if (-not $PSBoundParameters.ContainsKey('OutputPath')) { + $OutputPath = Join-Path -Path $ScriptsRoot -ChildPath 'Update-AllTheThings.ps1' +} + +$SourcePaths = @( + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Test-PSPreworkoutCommand.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Get-PSPreworkoutPlatform.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Write-UpdateAllTheThingsProgress.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Invoke-UpdateNativeCommand.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Get-CimOperatingSystemCaption.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Get-WmiOperatingSystemCaption.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Get-WindowsOperatingSystemCaption.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Read-WinGetServerChoice.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Invoke-WinGetUpgrade.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Invoke-GitHubCliExtensionUpgrade.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Invoke-GitHubCopilotCliUpdate.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Set-UpdateRepositoryTrust.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-PowerShellArtifact.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-WinGetPackage.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-LinuxPackage.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-MacOSPackage.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-OptionalCli.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Private\Update-ChocolateyPackage.ps1') + (Join-Path -Path $ModuleRoot -ChildPath 'Public\Test-IsElevated.ps1') + $UpdateCommandPath +) + +$ScriptInfoContent = Get-Content -LiteralPath $ScriptInfoPath -Raw +$UpdateCommandContent = Get-Content -LiteralPath $UpdateCommandPath -Raw +$NewLine = [string][char]13 + [string][char]10 -# Find the current version number in file Content2. $SemVerPattern = 'v(\d+)\.(\d+)\.(\d+)' -$SemVerMatch = [regex]::Match($Content2, $SemVerPattern) -# Remove the 'v' and incrememnt the manjor, minor, or build # if specified by function parameters. -$CurrentVersion = [version]$(($semVerMatch.Value).Replace('v', '')) +$SemVerMatch = [regex]::Match($UpdateCommandContent, $SemVerPattern) +if (-not $SemVerMatch.Success) { + throw "Unable to find a semantic version in '$UpdateCommandPath'." +} + +$CurrentVersion = [version]$SemVerMatch.Groups[0].Value.TrimStart('v') if ($CustomVersion) { - # Manually set a custom new version number. - $NewVersion = "v$($CustomVersion.Replace('v',''))" + $NewVersion = $CustomVersion } else { - $NewVersion = $CurrentVersion -} - -if ($Major -or $Minor -or $Patch) { - if ($VersionLevel -eq 'Major') { - $NewVersion = [version]::new($CurrentVersion.Major + 1, 0, 0) - $NewVersion = "v$($NewVersion)" - } - if ($VersionLevel -eq 'Minor') { - $NewVersion = [version]::new($CurrentVersion.Major, $CurrentVersion.Minor + 1, 0) - $NewVersion = "v$($NewVersion)" - } - if ($Versionlevel -eq 'Patch') { - $NewVersion = [version]::new($CurrentVersion.Major, $CurrentVersion.Minor, $CurrentVersion.Patch + 1) - $NewVersion = "v$($NewVersion)" + switch ($VersionLevel) { + 'Major' { + $NewVersion = [version]::new($CurrentVersion.Major + 1, 0, 0) + } + 'Minor' { + $NewVersion = [version]::new($CurrentVersion.Major, $CurrentVersion.Minor + 1, 0) + } + 'Patch' { + $NewVersion = [version]::new($CurrentVersion.Major, $CurrentVersion.Minor, $CurrentVersion.Build + 1) + } + default { + $NewVersion = $CurrentVersion + } } } -# Check the version number in PSScriptInfo. -$ScriptInfoVersion = $Content0 | Select-String -Pattern '.VERSION ((\d+).(\d+).(\d+))' -if ($NewVersion -ne $ScriptInfoVersion) { - # Align the version to the contents of the script if they are different. - $Content0 = $Content0.Replace($ScriptInfoVersion, ".VERSION $($NewVersion.ToString())") +$ScriptInfoVersionPattern = '(?m)^\.VERSION\s+\d+\.\d+\.\d+\s*$' +if (-not [regex]::IsMatch($ScriptInfoContent, $ScriptInfoVersionPattern)) { + throw "Unable to find a .VERSION declaration in '$ScriptInfoPath'." } -# Set the new version number in the contents of the script. -$Content2 = $Content2.Replace($($SemVerMatch.Value), $NewVersion) +$ScriptInfoContent = [regex]::Replace( + $ScriptInfoContent, + $ScriptInfoVersionPattern, + ".VERSION $NewVersion" +) +$UpdateCommandContent = $UpdateCommandContent.Replace($SemVerMatch.Value, "v$NewVersion") + +$GeneratedParts = @(($ScriptInfoContent -replace "`r`n?|\n", $NewLine).TrimEnd()) +foreach ($SourcePath in $SourcePaths) { + if ($SourcePath -eq $UpdateCommandPath) { + $GeneratedParts += ($UpdateCommandContent -replace "`r`n?|\n", $NewLine).TrimEnd() + } else { + $SourceContent = Get-Content -LiteralPath $SourcePath -Raw + $GeneratedParts += ($SourceContent -replace "`r`n?|\n", $NewLine).TrimEnd() + } +} -# Write the PSScriptInfo and scripts into the merged script. -$Content0 + $Content1 + $Content2 | Set-Content -Path 'Update-AllTheThings.ps1' +$GeneratedContent = ($GeneratedParts -join ($NewLine + $NewLine)) + $NewLine +$Utf8NoBom = [System.Text.UTF8Encoding]::new($false) +[System.IO.File]::WriteAllText($OutputPath, $GeneratedContent, $Utf8NoBom) if ($PSBoundParameters.ContainsKey('Publish')) { - # Publish-Script -Path ./Update-AllTheThings -NuGetApiKey ${{ secrets.POWERSHELLGALLERY_KEY }} + # Publish-Script -Path $OutputPath -NuGetApiKey ${{ secrets.POWERSHELLGALLERY_KEY }} } diff --git a/Scripts/Update-AllTheThings_ScriptInfo.ps1 b/Scripts/Update-AllTheThings_ScriptInfo.ps1 index d3d8b0c4..73cdfd9b 100644 --- a/Scripts/Update-AllTheThings_ScriptInfo.ps1 +++ b/Scripts/Update-AllTheThings_ScriptInfo.ps1 @@ -1,6 +1,6 @@ <#PSScriptInfo -.DESCRIPTION A script to automatically update all PowerShell modules, PowerShell Help, and packages (apt, brew, Chocolatey, winget). -.VERSION 0.5.8 +.DESCRIPTION A script to automatically update all PowerShell modules, PowerShell Help, GitHub CLI extensions, GitHub Copilot CLI, and packages (apt, brew, Chocolatey, WinGet). +.VERSION 0.6.0 .GUID 3a1a1ec9-0ef6-4f84-963d-be1505dab6a8 .AUTHOR Sam Erde .COPYRIGHT (c) 2024 Sam Erde. All rights reserved. diff --git a/docs/Update-AllTheThings.md b/docs/Update-AllTheThings.md index f12c61cb..72e1e41e 100644 --- a/docs/Update-AllTheThings.md +++ b/docs/Update-AllTheThings.md @@ -32,7 +32,9 @@ This cmdlet has the following aliases: ## DESCRIPTION -A script to automatically update all PowerShell modules, PowerShell Help, and packages (apt, brew, Chocolatey, winget). +A script to automatically update all PowerShell modules, PowerShell Help, +GitHub CLI extensions, GitHub Copilot CLI, and packages (apt, brew, +Chocolatey, WinGet). ## EXAMPLES @@ -46,13 +48,16 @@ Updates all of the things it can! Update-AllTheThings -AcceptPrompts -Updates all of the things and automatically accepts Linux package upgrade prompts. +Updates all of the things and automatically accepts Linux package upgrade +prompts and the additional WinGet confirmation prompt on Windows Server. ## PARAMETERS ### -AcceptPrompts -Automatically accept prompts to install updates in Linux (apt, dnf). +Automatically accept prompts to install updates in Linux (apt, dnf) and +continue WinGet updates on Windows Server without showing the extra server +confirmation prompt. ```yaml Type: System.Management.Automation.SwitchParameter @@ -180,7 +185,7 @@ HelpMessage: '' ### -SkipWinGet -Skip the step the updates WinGet packages. +Skip the step that updates WinGet packages. ```yaml Type: System.Management.Automation.SwitchParameter @@ -235,10 +240,9 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES Author: Sam Erde -Version: 0.5.10 +Version: 0.6.0 ## RELATED LINKS -{{ Fill in the related links here }} - +- [Update-AllTheThings](https://day3bits.com/PSPreworkout/Update-AllTheThings) diff --git a/src/PSPreworkout.build.ps1 b/src/PSPreworkout.build.ps1 index 045b50fa..429bf0c4 100644 --- a/src/PSPreworkout.build.ps1 +++ b/src/PSPreworkout.build.ps1 @@ -49,7 +49,7 @@ function Test-ManifestBool ($Path) { $str = @() $str = 'Clean', 'ValidateRequirements', 'ImportModuleManifest' $str += 'FormattingCheck' -$str += 'Analyze', 'Test' +$str += 'Test', 'Analyze' $str += 'CreateHelpStart' $str2 = $str $str2 += 'Build', 'Archive' @@ -57,7 +57,7 @@ $str += 'Build', 'IntegrationTest', 'Archive' Add-BuildTask -Name . -Jobs $str #Local testing build process -Add-BuildTask TestLocal Clean, ImportModuleManifest, Analyze, Test +Add-BuildTask TestLocal Clean, ImportModuleManifest, Test, Analyze #Local help file creation process Add-BuildTask HelpLocal Clean, ImportModuleManifest, CreateHelpStart @@ -312,8 +312,17 @@ Add-BuildTask FormattingCheck { Add-BuildTask Test { Write-Build White " Importing desired Pester version. Min: $script:MinPesterVersion Max: $script:MaxPesterVersion" - Remove-Module -Name Pester -Force -ErrorAction SilentlyContinue # there are instances where some containers have Pester already in the session - Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop' + $loadedPester = Get-Module -Name Pester | + Sort-Object -Property Version -Descending | + Select-Object -First 1 + if (-not $loadedPester) { + Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop' + } elseif ( + $loadedPester.Version -lt $script:MinPesterVersion -or + $loadedPester.Version -gt $script:MaxPesterVersion + ) { + throw "Loaded Pester version $($loadedPester.Version) is outside the supported range." + } $codeCovPath = "$script:ArtifactsPath\ccReport\" $testOutPutPath = "$script:ArtifactsPath\testOutput\" @@ -329,6 +338,7 @@ Add-BuildTask Test { $pesterConfiguration.Run.PassThru = $true $pesterConfiguration.Run.Exit = $false $pesterConfiguration.CodeCoverage.Enabled = $true + $pesterConfiguration.CodeCoverage.UseBreakpoints = $false # Fixed by inserting "\src" in front of \$ModuleName $pesterConfiguration.CodeCoverage.Path = "..\..\..\src\$ModuleName\*\*.ps1" $pesterConfiguration.CodeCoverage.CoveragePercentTarget = $script:coverageThreshold @@ -379,11 +389,21 @@ Add-BuildTask Test { Add-BuildTask DevCC { Write-Build White ' Generating code coverage report at root...' Write-Build White " Importing desired Pester version. Min: $script:MinPesterVersion Max: $script:MaxPesterVersion" - Remove-Module -Name Pester -Force -ErrorAction SilentlyContinue # there are instances where some containers have Pester already in the session - Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop' + $loadedPester = Get-Module -Name Pester | + Sort-Object -Property Version -Descending | + Select-Object -First 1 + if (-not $loadedPester) { + Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop' + } elseif ( + $loadedPester.Version -lt $script:MinPesterVersion -or + $loadedPester.Version -gt $script:MaxPesterVersion + ) { + throw "Loaded Pester version $($loadedPester.Version) is outside the supported range." + } $pesterConfiguration = New-PesterConfiguration $pesterConfiguration.run.Path = $script:UnitTestsPath $pesterConfiguration.CodeCoverage.Enabled = $true + $pesterConfiguration.CodeCoverage.UseBreakpoints = $false $pesterConfiguration.CodeCoverage.Path = "$PSScriptRoot\$ModuleName\*\*.ps1" $pesterConfiguration.CodeCoverage.CoveragePercentTarget = $script:coverageThreshold $pesterConfiguration.CodeCoverage.OutputPath = '..\..\..\cov.xml' diff --git a/src/PSPreworkout/Private/Get-CimOperatingSystemCaption.ps1 b/src/PSPreworkout/Private/Get-CimOperatingSystemCaption.ps1 new file mode 100644 index 00000000..cb62838f --- /dev/null +++ b/src/PSPreworkout/Private/Get-CimOperatingSystemCaption.ps1 @@ -0,0 +1,24 @@ +function Get-CimOperatingSystemCaption { + <# + .SYNOPSIS + Gets the operating-system caption through CIM. + + .DESCRIPTION + Queries CIM_OperatingSystem and returns its caption. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Query = { + (Get-CimInstance -ClassName CIM_OperatingSystem -ErrorAction Stop).Caption + } + ) + + return & $Query +} diff --git a/src/PSPreworkout/Private/Get-PSPreworkoutPlatform.ps1 b/src/PSPreworkout/Private/Get-PSPreworkoutPlatform.ps1 new file mode 100644 index 00000000..eea2a77a --- /dev/null +++ b/src/PSPreworkout/Private/Get-PSPreworkoutPlatform.ps1 @@ -0,0 +1,33 @@ +function Get-PSPreworkoutPlatform { + <# + .SYNOPSIS + Gets the current operating-system platform. + + .DESCRIPTION + Returns a stable platform name across Windows PowerShell 5.1 and PowerShell 7. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param() + + if ($PSVersionTable.PSEdition -eq 'Desktop') { + return 'Windows' + } + if (Get-Variable -Name IsWindows -ValueOnly -ErrorAction SilentlyContinue) { + return 'Windows' + } + + if (Get-Variable -Name IsLinux -ValueOnly -ErrorAction SilentlyContinue) { + return 'Linux' + } + + if (Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue) { + return 'macOS' + } + + return 'Unknown' +} diff --git a/src/PSPreworkout/Private/Get-WindowsOperatingSystemCaption.ps1 b/src/PSPreworkout/Private/Get-WindowsOperatingSystemCaption.ps1 new file mode 100644 index 00000000..d772ceda --- /dev/null +++ b/src/PSPreworkout/Private/Get-WindowsOperatingSystemCaption.ps1 @@ -0,0 +1,33 @@ +function Get-WindowsOperatingSystemCaption { + <# + .SYNOPSIS + Gets the Windows operating-system caption. + + .DESCRIPTION + Uses CIM when available and falls back to WMI for Windows PowerShell 5.1 + environments where the CimCmdlets module is unavailable. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + param() + + if (Test-PSPreworkoutCommand -Name 'Get-CimInstance') { + try { + return Get-CimOperatingSystemCaption + } catch { + Write-Verbose 'Get-CimInstance failed while checking the Windows operating system caption.' + } + } + + if (Test-PSPreworkoutCommand -Name 'Get-WmiObject') { + try { + return Get-WmiOperatingSystemCaption + } catch { + Write-Verbose 'Get-WmiObject failed while checking the Windows operating system caption.' + } + } +} diff --git a/src/PSPreworkout/Private/Get-WmiOperatingSystemCaption.ps1 b/src/PSPreworkout/Private/Get-WmiOperatingSystemCaption.ps1 new file mode 100644 index 00000000..f2dfc801 --- /dev/null +++ b/src/PSPreworkout/Private/Get-WmiOperatingSystemCaption.ps1 @@ -0,0 +1,30 @@ +function Get-WmiOperatingSystemCaption { + <# + .SYNOPSIS + Gets the operating-system caption through WMI. + + .DESCRIPTION + Queries Win32_OperatingSystem and returns its caption for Windows PowerShell + 5.1 environments where CimCmdlets are unavailable. + + .OUTPUTS + System.String + #> + + [CmdletBinding()] + [OutputType([string])] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSAvoidUsingWMICmdlet', + '', + Justification = 'Get-WmiObject is required as a Windows PowerShell 5.1 fallback when CimCmdlets are unavailable.' + )] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Query = { + (Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop).Caption + } + ) + + return & $Query +} diff --git a/src/PSPreworkout/Private/Invoke-GitHubCliExtensionUpgrade.ps1 b/src/PSPreworkout/Private/Invoke-GitHubCliExtensionUpgrade.ps1 new file mode 100644 index 00000000..5713a4b9 --- /dev/null +++ b/src/PSPreworkout/Private/Invoke-GitHubCliExtensionUpgrade.ps1 @@ -0,0 +1,27 @@ +function Invoke-GitHubCliExtensionUpgrade { + <# + .SYNOPSIS + Upgrades installed GitHub CLI extensions. + + .DESCRIPTION + Invokes the GitHub CLI extension upgrade command and throws when it fails. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & gh extension upgrade --all | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "GitHub CLI extension upgrade failed with exit code $ExitCode." + } +} diff --git a/src/PSPreworkout/Private/Invoke-GitHubCopilotCliUpdate.ps1 b/src/PSPreworkout/Private/Invoke-GitHubCopilotCliUpdate.ps1 new file mode 100644 index 00000000..3931c3b1 --- /dev/null +++ b/src/PSPreworkout/Private/Invoke-GitHubCopilotCliUpdate.ps1 @@ -0,0 +1,27 @@ +function Invoke-GitHubCopilotCliUpdate { + <# + .SYNOPSIS + Updates the GitHub Copilot CLI. + + .DESCRIPTION + Invokes the GitHub Copilot CLI update command and throws when it fails. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & copilot update | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "GitHub Copilot CLI update failed with exit code $ExitCode." + } +} diff --git a/src/PSPreworkout/Private/Invoke-UpdateNativeCommand.ps1 b/src/PSPreworkout/Private/Invoke-UpdateNativeCommand.ps1 new file mode 100644 index 00000000..af2fd73c --- /dev/null +++ b/src/PSPreworkout/Private/Invoke-UpdateNativeCommand.ps1 @@ -0,0 +1,54 @@ +function Invoke-UpdateNativeCommand { + <# + .SYNOPSIS + Invokes a native update command and validates its exit code. + + .DESCRIPTION + Provides consistent invocation and explicit failure handling for native + package-manager commands. + + .PARAMETER Name + The native command to invoke. + + .PARAMETER ArgumentList + Arguments passed to the native command. + + .PARAMETER FailureMessage + Context included in the terminating error when the command fails. + + .PARAMETER Command + An invocation seam used by unit tests. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$Name, + + [Parameter()] + [AllowEmptyCollection()] + [string[]]$ArgumentList = @(), + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$FailureMessage, + + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + param($CommandName, $CommandArguments) + + & $CommandName @CommandArguments | Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command $Name $ArgumentList + if ($ExitCode -ne 0) { + throw "$FailureMessage failed with exit code $ExitCode." + } +} diff --git a/src/PSPreworkout/Private/Invoke-WinGetUpgrade.ps1 b/src/PSPreworkout/Private/Invoke-WinGetUpgrade.ps1 new file mode 100644 index 00000000..083a6c0d --- /dev/null +++ b/src/PSPreworkout/Private/Invoke-WinGetUpgrade.ps1 @@ -0,0 +1,28 @@ +function Invoke-WinGetUpgrade { + <# + .SYNOPSIS + Upgrades all user-scoped WinGet packages. + + .DESCRIPTION + Invokes WinGet non-interactively and throws when WinGet reports a failure. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [scriptblock]$Command = { + & winget upgrade --silent --scope user --accept-package-agreements --accept-source-agreements --all | + Out-Host + return $LASTEXITCODE + } + ) + + $ExitCode = & $Command + if ($ExitCode -ne 0) { + throw "WinGet package upgrade failed with exit code $ExitCode." + } +} diff --git a/src/PSPreworkout/Private/Read-WinGetServerChoice.ps1 b/src/PSPreworkout/Private/Read-WinGetServerChoice.ps1 new file mode 100644 index 00000000..7291af8b --- /dev/null +++ b/src/PSPreworkout/Private/Read-WinGetServerChoice.ps1 @@ -0,0 +1,32 @@ +function Read-WinGetServerChoice { + <# + .SYNOPSIS + Prompts before updating packages on Windows Server. + + .DESCRIPTION + Shows a host choice prompt that defaults to declining WinGet package updates. + + .OUTPUTS + System.Int32 + #> + + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(DontShow)] + [ValidateNotNull()] + [object]$HostUserInterface = $Host.UI + ) + + $Options = [System.Management.Automation.Host.ChoiceDescription[]]@( + [System.Management.Automation.Host.ChoiceDescription]::new('&Yes', 'Continue with WinGet package updates.') + [System.Management.Automation.Host.ChoiceDescription]::new('&No', 'Skip WinGet package updates.') + ) + + return $HostUserInterface.PromptForChoice( + 'Windows Server OS Found', + "Do you want to run 'winget upgrade' on your server?", + $Options, + 1 + ) +} diff --git a/src/PSPreworkout/Private/Set-UpdateRepositoryTrust.ps1 b/src/PSPreworkout/Private/Set-UpdateRepositoryTrust.ps1 new file mode 100644 index 00000000..4a7a520f --- /dev/null +++ b/src/PSPreworkout/Private/Set-UpdateRepositoryTrust.ps1 @@ -0,0 +1,32 @@ +function Set-UpdateRepositoryTrust { + <# + .SYNOPSIS + Trusts supported PowerShell Gallery repositories. + + .DESCRIPTION + Configures PSGallery as trusted for the installed PowerShellGet and + PSResourceGet clients. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param() + + Write-Verbose 'Set the PowerShell Gallery as a trusted installation source.' + + if ( + (Test-PSPreworkoutCommand -Name 'Set-PSRepository') -and + $PSCmdlet.ShouldProcess('PSGallery', 'Set PowerShellGet repository as trusted') + ) { + Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted + } + + if ( + (Test-PSPreworkoutCommand -Name 'Set-PSResourceRepository') -and + $PSCmdlet.ShouldProcess('PSGallery', 'Set PSResourceGet repository as trusted') + ) { + Set-PSResourceRepository -Name 'PSGallery' -Trusted + } +} diff --git a/src/PSPreworkout/Private/Test-PSPreworkoutCommand.ps1 b/src/PSPreworkout/Private/Test-PSPreworkoutCommand.ps1 new file mode 100644 index 00000000..829cda13 --- /dev/null +++ b/src/PSPreworkout/Private/Test-PSPreworkoutCommand.ps1 @@ -0,0 +1,25 @@ +function Test-PSPreworkoutCommand { + <# + .SYNOPSIS + Tests whether a command is available. + + .DESCRIPTION + Resolves a command without emitting an error and returns whether it was found. + + .PARAMETER Name + The name of the command to resolve. + + .OUTPUTS + System.Boolean + #> + + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$Name + ) + + return $null -ne (Get-Command -Name $Name -ErrorAction SilentlyContinue) +} diff --git a/src/PSPreworkout/Private/Update-ChocolateyPackage.ps1 b/src/PSPreworkout/Private/Update-ChocolateyPackage.ps1 new file mode 100644 index 00000000..6aa005ee --- /dev/null +++ b/src/PSPreworkout/Private/Update-ChocolateyPackage.ps1 @@ -0,0 +1,53 @@ +function Update-ChocolateyPackage { + <# + .SYNOPSIS + Updates Chocolatey and installed Chocolatey packages. + + .DESCRIPTION + Optionally configures Chocolatey features when elevated, then updates + Chocolatey and all installed packages. + + .PARAMETER Include + Enables Chocolatey package updates. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$Include + ) + + if ((-not $Include) -or (-not (Test-PSPreworkoutCommand -Name 'choco'))) { + Write-Information '[9] Skipping Chocolatey' -InformationAction Continue + return + } + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating Chocolatey Packages' -PercentComplete 98 + Write-Information '[9] Updating Chocolatey Packages' -InformationAction Continue + + if (Test-IsElevated) { + if ($PSCmdlet.ShouldProcess('Chocolatey features', 'Enable global confirmation and disable non-elevated warnings')) { + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList @( + 'feature', 'enable', '-n=allowGlobalConfirmation' + ) -FailureMessage 'Chocolatey global confirmation configuration' + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList @( + 'feature', 'disable', '--name=showNonElevatedWarnings' + ) -FailureMessage 'Chocolatey non-elevated warning configuration' + } + } else { + Write-Verbose "Run once as an administrator to disable Chocolatey's showNonElevatedWarnings." -Verbose + } + + if ($PSCmdlet.ShouldProcess('Chocolatey packages', 'Upgrade Chocolatey and all packages')) { + $UpgradeArguments = @('-y', '--limit-output', '--accept-license', '--no-color') + $SelfUpdateArguments = @('upgrade', 'chocolatey') + $UpgradeArguments + $PackageUpdateArguments = @('upgrade', 'all') + $UpgradeArguments + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList $SelfUpdateArguments -FailureMessage 'Chocolatey self-update' + Invoke-UpdateNativeCommand -Name 'choco' -ArgumentList $PackageUpdateArguments -FailureMessage 'Chocolatey package update' + } + + Write-Information ' ' -InformationAction Continue +} diff --git a/src/PSPreworkout/Private/Update-LinuxPackage.ps1 b/src/PSPreworkout/Private/Update-LinuxPackage.ps1 new file mode 100644 index 00000000..deeabdd8 --- /dev/null +++ b/src/PSPreworkout/Private/Update-LinuxPackage.ps1 @@ -0,0 +1,58 @@ +function Update-LinuxPackage { + <# + .SYNOPSIS + Updates packages with supported Linux package managers. + + .DESCRIPTION + Updates apt and dnf packages, using sudo only when the current process is + not elevated. + + .PARAMETER AcceptPrompts + Passes the non-interactive acceptance argument to package managers. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$AcceptPrompts + ) + + $AptAvailable = Test-PSPreworkoutCommand -Name 'apt' + $DnfAvailable = Test-PSPreworkoutCommand -Name 'dnf' + if ((-not $AptAvailable) -and (-not $DnfAvailable)) { + return + } + + $NeedsSudo = -not (Test-IsElevated) + + if ($AptAvailable) { + Write-Information '[5] Updating apt packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('apt packages', 'Update and upgrade packages')) { + $CommandName = if ($NeedsSudo) { 'sudo' } else { 'apt' } + $UpdateArguments = if ($NeedsSudo) { @('apt', 'update') } else { @('update') } + [string[]]$UpgradeArguments = if ($NeedsSudo) { @('apt', 'upgrade') } else { @('upgrade') } + if ($AcceptPrompts) { + $UpgradeArguments += '-y' + } + + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $UpdateArguments -FailureMessage 'apt package index update' + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $UpgradeArguments -FailureMessage 'apt package upgrade' + } + } + + if ($DnfAvailable) { + Write-Information '[5] Updating dnf packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('dnf packages', 'Update packages')) { + $CommandName = if ($NeedsSudo) { 'sudo' } else { 'dnf' } + [string[]]$Arguments = if ($NeedsSudo) { @('dnf', 'update') } else { @('update') } + if ($AcceptPrompts) { + $Arguments += '-y' + } + + Invoke-UpdateNativeCommand -Name $CommandName -ArgumentList $Arguments -FailureMessage 'dnf package update' + } + } +} diff --git a/src/PSPreworkout/Private/Update-MacOSPackage.ps1 b/src/PSPreworkout/Private/Update-MacOSPackage.ps1 new file mode 100644 index 00000000..e5f4c00c --- /dev/null +++ b/src/PSPreworkout/Private/Update-MacOSPackage.ps1 @@ -0,0 +1,28 @@ +function Update-MacOSPackage { + <# + .SYNOPSIS + Updates supported macOS software. + + .DESCRIPTION + Lists macOS software updates and updates Homebrew packages when Homebrew is + installed. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param() + + if ($PSCmdlet.ShouldProcess('macOS software updates', 'List available updates')) { + Invoke-UpdateNativeCommand -Name 'softwareupdate' -ArgumentList '-l' -FailureMessage 'macOS software update query' + } + + if (Test-PSPreworkoutCommand -Name 'brew') { + Write-Information '[6] Updating brew packages.' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('Homebrew packages', 'Update and upgrade packages')) { + Invoke-UpdateNativeCommand -Name 'brew' -ArgumentList 'update' -FailureMessage 'Homebrew update' + Invoke-UpdateNativeCommand -Name 'brew' -ArgumentList 'upgrade' -FailureMessage 'Homebrew upgrade' + } + } +} diff --git a/src/PSPreworkout/Private/Update-OptionalCli.ps1 b/src/PSPreworkout/Private/Update-OptionalCli.ps1 new file mode 100644 index 00000000..5d3716ba --- /dev/null +++ b/src/PSPreworkout/Private/Update-OptionalCli.ps1 @@ -0,0 +1,75 @@ +function Update-OptionalCli { + <# + .SYNOPSIS + Updates an optional command-line tool. + + .DESCRIPTION + Runs a supplied update command when its command-line tool is installed. + + .PARAMETER CommandName + The command used to detect whether the tool is installed. + + .PARAMETER DisplayName + The status text displayed to the user. + + .PARAMETER CurrentOperation + The operation shown in the progress record. + + .PARAMETER TargetName + The ShouldProcess target. + + .PARAMETER ActionName + The ShouldProcess action. + + .PARAMETER PercentComplete + The overall completion percentage. + + .PARAMETER UpdateCommand + The update operation to invoke. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$CommandName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$DisplayName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$CurrentOperation, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$TargetName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$ActionName, + + [Parameter(Mandatory)] + [ValidateRange(0, 100)] + [int]$PercentComplete, + + [Parameter(Mandatory)] + [ValidateNotNull()] + [scriptblock]$UpdateCommand + ) + + if (-not (Test-PSPreworkoutCommand -Name $CommandName)) { + Write-Verbose "$DisplayName was skipped because $CommandName was not found." + return + } + + Write-Information $DisplayName -InformationAction Continue + Write-UpdateAllTheThingsProgress -CurrentOperation $CurrentOperation -PercentComplete $PercentComplete + if ($PSCmdlet.ShouldProcess($TargetName, $ActionName)) { + & $UpdateCommand + } +} diff --git a/src/PSPreworkout/Private/Update-PowerShellArtifact.ps1 b/src/PSPreworkout/Private/Update-PowerShellArtifact.ps1 new file mode 100644 index 00000000..7659ed28 --- /dev/null +++ b/src/PSPreworkout/Private/Update-PowerShellArtifact.ps1 @@ -0,0 +1,98 @@ +function Update-PowerShellArtifact { + <# + .SYNOPSIS + Updates installed PowerShell modules, scripts, and help. + + .DESCRIPTION + Handles PowerShell-native update operations and their progress reporting. + + .PARAMETER SkipModules + Skips installed module updates. + + .PARAMETER SkipScripts + Skips installed script updates. + + .PARAMETER SkipHelp + Skips PowerShell help updates. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$SkipModules, + + [Parameter()] + [switch]$SkipScripts, + + [Parameter()] + [switch]$SkipHelp + ) + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Getting Installed PowerShell Modules' -PercentComplete 1 + + if ($SkipModules) { + Write-Information '[1] Skipping PowerShell Modules' -InformationAction Continue + } elseif (-not (Test-PSPreworkoutCommand -Name 'Get-InstalledModule')) { + Write-Warning 'Get-InstalledModule was not found. Skipping PowerShell module updates.' + } else { + Write-Information '[1] Getting Installed PowerShell Modules' -InformationAction Continue + $Modules = @(Get-InstalledModule) + Write-Information "[2] Updating $($Modules.Count) PowerShell Modules" -InformationAction Continue + + $ModuleIndex = 0 + foreach ($Module in $Modules) { + ++$ModuleIndex + $ModulePercent = [math]::Ceiling(($ModuleIndex / $Modules.Count) * 100) + $OverallPercent = [math]::Ceiling(10 + (60 * ($ModulePercent / 100))) + + Write-UpdateAllTheThingsProgress -CurrentOperation "Updating PowerShell module $($Module.Name)" -PercentComplete $OverallPercent + Write-Progress -Id 1 -ParentId 0 -Activity 'Updating PowerShell Modules' ` + -CurrentOperation $Module.Name -Status "Progress: $ModulePercent`% Complete" ` + -PercentComplete $ModulePercent + + if ($Module.Version -match 'alpha|beta|prerelease|preview') { + Write-Information "`t`tSkipping $($Module.Name) because a prerelease version is currently installed." -InformationAction Continue + continue + } + + try { + if ($PSCmdlet.ShouldProcess($Module.Name, 'Update PowerShell module')) { + Update-Module -Name $Module.Name + } + } catch [Microsoft.PowerShell.Commands.WriteErrorException] { + Write-Warning "Unable to update PowerShell module '$($Module.Name)': $($_.Exception.Message)" + } + } + } + + Write-Progress -Id 1 -Activity 'Updating PowerShell Modules' -Completed + + if ($SkipScripts) { + Write-Information '[2] Skipping PowerShell Scripts' -InformationAction Continue + } elseif (-not (Test-PSPreworkoutCommand -Name 'Update-Script')) { + Write-Warning 'Update-Script was not found. Skipping PowerShell script updates.' + } else { + Write-Information '[2] Updating PowerShell Scripts' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('Installed PowerShell scripts', 'Update scripts')) { + Update-Script + } + } + + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating PowerShell Help' -PercentComplete 70 + + if ($SkipHelp) { + Write-Information '[3] Skipping PowerShell Help' -InformationAction Continue + } else { + Write-Information '[3] Updating PowerShell Help' -InformationAction Continue + if ($PSCmdlet.ShouldProcess('PowerShell help files', 'Update help')) { + if ((Get-Culture).LCID -eq 127) { + Update-Help -UICulture en-US -ErrorAction SilentlyContinue + } else { + Update-Help -ErrorAction SilentlyContinue + } + } + } +} diff --git a/src/PSPreworkout/Private/Update-WinGetPackage.ps1 b/src/PSPreworkout/Private/Update-WinGetPackage.ps1 new file mode 100644 index 00000000..5bfd03f1 --- /dev/null +++ b/src/PSPreworkout/Private/Update-WinGetPackage.ps1 @@ -0,0 +1,72 @@ +function Update-WinGetPackage { + <# + .SYNOPSIS + Updates user-scoped WinGet packages. + + .DESCRIPTION + Applies Windows Server safeguards before invoking WinGet. + + .PARAMETER Skip + Skips WinGet package updates. + + .PARAMETER AcceptPrompts + Bypasses the additional Windows Server confirmation prompt. + + .OUTPUTS + None + #> + + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter()] + [switch]$Skip, + + [Parameter()] + [switch]$AcceptPrompts + ) + + if ($Skip) { + Write-Information '[4] Skipping WinGet' -InformationAction Continue + return + } + + if (-not (Test-PSPreworkoutCommand -Name 'winget')) { + Write-Information '[4] WinGet was not found. Skipping WinGet update.' -InformationAction Continue + return + } + + $ShouldUpdate = $PSCmdlet.ShouldProcess('WinGet packages', 'Upgrade all user-scoped packages') + $SkipServerPrompt = $AcceptPrompts -or $WhatIfPreference -or ( + $PSBoundParameters.ContainsKey('Confirm') -and (-not $Confirm) + ) + $ShouldProcessHandlesConsent = ($PSBoundParameters.ContainsKey('Confirm') -and $Confirm) -or ( + ($ConfirmPreference -ne [System.Management.Automation.ConfirmImpact]::None) -and + (([System.Management.Automation.ConfirmImpact]$ConfirmPreference) -le [System.Management.Automation.ConfirmImpact]::Medium) + ) + $NeedServerPrompt = (-not $SkipServerPrompt) -and (-not $ShouldProcessHandlesConsent) + + if ($NeedServerPrompt) { + $WindowsOsCaption = Get-WindowsOperatingSystemCaption + if ([string]::IsNullOrWhiteSpace($WindowsOsCaption)) { + Write-Warning -Message 'Unable to determine the Windows operating system caption. Skipping WinGet updates as a safety precaution.' + return + } + + if ($ShouldUpdate -and ($WindowsOsCaption -match 'Server')) { + Write-Warning -Message 'This is a server and updates could affect production systems. Do you want to continue with updating packages?' + if ((Read-WinGetServerChoice) -ne 0) { + return + } + Write-Verbose 'Continuing with WinGet package updates.' + } + } + + if ($ShouldUpdate -or $WhatIfPreference) { + Write-Information '[4] Updating WinGet Packages' -InformationAction Continue + Write-UpdateAllTheThingsProgress -CurrentOperation 'Updating WinGet Packages' -PercentComplete 80 + } + + if ($ShouldUpdate) { + Invoke-WinGetUpgrade + } +} diff --git a/src/PSPreworkout/Private/Write-UpdateAllTheThingsProgress.ps1 b/src/PSPreworkout/Private/Write-UpdateAllTheThingsProgress.ps1 new file mode 100644 index 00000000..964fee4c --- /dev/null +++ b/src/PSPreworkout/Private/Write-UpdateAllTheThingsProgress.ps1 @@ -0,0 +1,50 @@ +function Write-UpdateAllTheThingsProgress { + <# + .SYNOPSIS + Writes progress for Update-AllTheThings. + + .DESCRIPTION + Centralizes the parent progress record used by Update-AllTheThings and its + private update helpers. + + .PARAMETER CurrentOperation + The operation currently being performed. + + .PARAMETER PercentComplete + The percentage of the overall update that is complete. + + .PARAMETER Completed + Completes and removes the progress record. + + .OUTPUTS + None + #> + + [CmdletBinding()] + param( + [Parameter()] + [ValidateNotNullOrEmpty()] + [string]$CurrentOperation, + + [Parameter()] + [ValidateRange(0, 100)] + [int]$PercentComplete = 0, + + [Parameter()] + [switch]$Completed + ) + + if ($Completed) { + Write-Progress -Id 0 -Activity 'Update Everything' -Completed + return + } + + $ProgressParameters = @{ + Id = 0 + Activity = 'Update Everything' + CurrentOperation = $CurrentOperation + Status = "Progress: $PercentComplete`% Complete" + PercentComplete = $PercentComplete + } + Write-Progress @ProgressParameters +} diff --git a/src/PSPreworkout/Public/Test-IsElevated.ps1 b/src/PSPreworkout/Public/Test-IsElevated.ps1 index 536933f7..86fdcde0 100644 --- a/src/PSPreworkout/Public/Test-IsElevated.ps1 +++ b/src/PSPreworkout/Public/Test-IsElevated.ps1 @@ -17,8 +17,10 @@ function Test-IsElevated { [OutputType([bool])] param () - # Send non-identifying usage statistics to PostHog. - Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + # The standalone Update-AllTheThings script does not include module telemetry. + if (Get-Command -Name Write-PSPreworkoutTelemetry -CommandType Function -ErrorAction SilentlyContinue) { + Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + } if (($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows) { $CurrentUser = [Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent()) @@ -49,7 +51,7 @@ function Test-IsElevated { # Check if we're on macOS and if user is in admin or wheel groups if ($IsMacOS -or (Get-Command 'sw_vers' -ErrorAction SilentlyContinue)) { # Method 3a: Use groups command to check admin group membership - $groups = & Get-Groups 2>$null + $groups = & groups 2>$null if ($LASTEXITCODE -eq 0 -and $groups) { $groupList = $groups -split '\s+' if ($groupList -contains 'admin' -or $groupList -contains 'wheel') { diff --git a/src/PSPreworkout/Public/Update-AllTheThings.ps1 b/src/PSPreworkout/Public/Update-AllTheThings.ps1 index 755a798c..067986fd 100644 --- a/src/PSPreworkout/Public/Update-AllTheThings.ps1 +++ b/src/PSPreworkout/Public/Update-AllTheThings.ps1 @@ -4,7 +4,7 @@ function Update-AllTheThings { Update all the things! .DESCRIPTION - A script to automatically update all PowerShell modules, PowerShell Help, and packages (apt, brew, Chocolatey, winget). + A script to automatically update all PowerShell modules, PowerShell Help, GitHub CLI extensions, GitHub Copilot CLI, and packages (apt, brew, Chocolatey, WinGet). .PARAMETER SkipModules Skip the step that updates PowerShell modules. @@ -16,13 +16,13 @@ function Update-AllTheThings { Skip the step that updates PowerShell help. .PARAMETER SkipWinGet - Skip the step the updates WinGet packages. + Skip the step that updates WinGet packages. .PARAMETER IncludeChocolatey Include Chocolatey package updates. .PARAMETER AcceptPrompts - Automatically accept prompts to install updates in Linux (apt, dnf). + Automatically accept prompts to install updates in Linux (apt, dnf) and continue WinGet updates on Windows Server without showing the extra server confirmation prompt. .EXAMPLE Update-AllTheThings @@ -32,58 +32,54 @@ function Update-AllTheThings { .EXAMPLE Update-AllTheThings -AcceptPrompts - Updates all of the things and automatically accepts Linux package upgrade prompts. + Updates all of the things and automatically accepts Linux package upgrade prompts and the additional WinGet confirmation prompt on Windows Server. .NOTES Author: Sam Erde - Version: 0.5.10 + Version: 0.6.0 #> [CmdletBinding( SupportsShouldProcess, + ConfirmImpact = 'Medium', HelpUri = 'https://day3bits.com/PSPreworkout/Update-AllTheThings' )] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'This is what we do.')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive Use')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '', Justification = 'WhatIf and Confirm are forwarded to private helpers that call ShouldProcess.')] [Alias('uatt')] param ( # Skip the step that updates PowerShell modules [Parameter()] - [switch] - $SkipModules, + [switch]$SkipModules, # Skip the step that updates PowerShell scripts [Parameter()] - [switch] - $SkipScripts, + [switch]$SkipScripts, # Skip the step that updates PowerShell help [Parameter()] - [switch] - $SkipHelp, + [switch]$SkipHelp, # Skip the step that updates WinGet packages [Parameter()] - [switch] - $SkipWinGet, + [switch]$SkipWinGet, - # Skip the step that updates Chocolatey packages + # Include Chocolatey package updates [Parameter()] [Alias('SkipChoco')] - [switch] - $IncludeChocolatey, + [switch]$IncludeChocolatey, - # Automatically accept prompts to install updates in Linux + # Automatically accept prompts to install updates [Parameter()] - [switch] - $AcceptPrompts + [switch]$AcceptPrompts ) begin { - # Send non-identifying usage statistics to PostHog. - Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + if (Test-PSPreworkoutCommand -Name 'Write-PSPreworkoutTelemetry') { + Write-PSPreworkoutTelemetry -EventName $MyInvocation.MyCommand.Name -ParameterNamesOnly $MyInvocation.BoundParameters.Keys + } - # Spacing to get host output from script, winget, and choco all below the progress bar. $Banner = @" __ __ __ __ ___ ____ / / / /__ ___/ /__ _/ /____ / _ | / / / @@ -93,311 +89,74 @@ function Update-AllTheThings { /_ __/ / ___ /_ __/ / (_)__ ___ ____ / / / _ \/ -_) / / / _ \/ / _ \/ _ `(_-< /_/ /_//_/\__/ /_/ /_//_/_/_//_/\_, /___/ - /___/ v0.5.9 + /___/ v0.6.0 "@ Write-Host $Banner - } # end begin block + } process { - Write-Verbose 'Set the PowerShell Gallery as a trusted installation source.' - if ($PSCmdlet.ShouldProcess('PSGallery', 'Set PowerShellGet repository as trusted')) { - Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted - } - if (Get-Command -Name Set-PSResourceRepository -ErrorAction SilentlyContinue) { - if ($PSCmdlet.ShouldProcess('PSGallery', 'Set PSResourceGet repository as trusted')) { - Set-PSResourceRepository -Name 'PSGallery' -Trusted - } - } - - #region UpdatePowerShell - - # ==================== Update PowerShell Modules ==================== - - # Update the outer progress bar - $PercentCompleteOuter = 1 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Getting Installed PowerShell Modules' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - if (-not $SkipModules) { - # Get all installed PowerShell modules - Write-Host '[1] Getting Installed PowerShell Modules' - $Modules = (Get-InstalledModule) - $ModuleCount = $Modules.Count - Write-Host "[2] Updating $ModuleCount PowerShell Modules" - } else { - Write-Host '[1] Skipping PowerShell Modules' - } - - # Estimate 10% progress so far and 70% at the next step - $PercentCompleteOuter_Modules = 10 - [int]$Module_i = 0 - - # Update all PowerShell modules - foreach ($module in $Modules) { - # Update the module loop counter and percent complete for both progress bars - ++$Module_i - [double]$PercentCompleteInner = [math]::ceiling( (($Module_i / $ModuleCount) * 100) ) - [double]$PercentCompleteOuter = [math]::ceiling( $PercentCompleteOuter_Modules + (60 * ($PercentCompleteInner / 100)) ) - - # Update the outer progress bar while updating modules - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - # Update the child progress bar while updating modules - $ProgressParam1 = @{ - Id = 1 - ParentId = 0 - Activity = 'Updating PowerShell Modules' - CurrentOperation = "$($module.Name)" - Status = "Progress: $PercentCompleteInner`% Complete" - PercentComplete = $PercentCompleteInner - } - Write-Progress @ProgressParam1 - - # Do not update prerelease modules - if ($module.Version -match 'alpha|beta|prerelease|preview') { - Write-Information "`t`tSkipping $($module.Name) because a prerelease version is currently installed." -InformationAction Continue - continue - } - - # Finally update the current module - try { - if ($PSCmdlet.ShouldProcess($module.Name, 'Update PowerShell module')) { - Update-Module $module.Name - } - } catch [Microsoft.PowerShell.Commands.WriteErrorException] { - # Add a catch for mismatched certificates between module versions. - Write-Verbose $_ - } - } - - # ##### Add a section for installed scripts +++++ - if (-not $SkipScripts) { - Write-Host '[2] Updating PowerShell Scripts' - if ($PSCmdlet.ShouldProcess('Installed PowerShell scripts', 'Update scripts')) { - Update-Script - } - } else { - Write-Host '[2] Skipping PowerShell Scripts' - } - # ##### Add a section for installed scripts +++++ - - # Complete the child progress bar after updating modules - Write-Progress -Id 1 -Activity 'Updating PowerShell Modules' -Completed - - - # ==================== Update PowerShell Help ==================== - - # Update the outer progress bar while updating help - $PercentCompleteOuter = 70 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating PowerShell Help' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - - if (-not $SkipHelp) { - Write-Host '[3] Updating PowerShell Help' - # Fixes error with culture ID 127 (Invariant Country), which is not associated with any language - if ($PSCmdlet.ShouldProcess('PowerShell help files', 'Update help')) { - if ((Get-Culture).LCID -eq 127) { - Update-Help -UICulture en-US -ErrorAction SilentlyContinue - } else { - Update-Help -ErrorAction SilentlyContinue - } + $CommonParameters = @{} + foreach ($CommonParameterName in 'WhatIf', 'Confirm') { + if ($PSBoundParameters.ContainsKey($CommonParameterName)) { + $CommonParameters[$CommonParameterName] = $PSBoundParameters[$CommonParameterName] } - } else { - Write-Host '[3] Skipping PowerShell Help' } - #endregion UpdatePowerShell - - #region UpdateWinget - # >>> Create a section to check OS and client/server OS at the top of the script <<< # - if ($IsWindows -or ($PSVersionTable.PSVersion -le [version]'5.1')) { - if ((Get-CimInstance -ClassName CIM_OperatingSystem).Caption -match 'Server') { - # If on Windows Server, prompt to continue before automatically updating packages. - Write-Warning -Message 'This is a server and updates could affect production systems. Do you want to continue with updating packages?' + $Platform = Get-PSPreworkoutPlatform - $Yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Description.' - $No = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'Description.' - $Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No) + Set-UpdateRepositoryTrust @CommonParameters + Update-PowerShellArtifact -SkipModules:$SkipModules -SkipScripts:$SkipScripts -SkipHelp:$SkipHelp @CommonParameters - $Title = 'Windows Server OS Found' - $Message = "Do you want to run 'winget update' on your server?" - $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, 1) - switch ($Result) { - 0 { - continue - } - 1 { - $SkipWinGet = $true - } - } - } - - if (-not $SkipWinGet) { - # Update all winget packages - Write-Host '[4] Updating Winget Packages' - # Update the outer progress bar for winget section - $PercentCompleteOuter = 80 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating Winget Packages' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - if (Get-Command winget -ErrorAction SilentlyContinue) { - if ($PSCmdlet.ShouldProcess('WinGet packages', 'Upgrade all user-scoped packages')) { - winget upgrade --silent --scope user --accept-package-agreements --accept-source-agreements --all - } - } else { - Write-Host '[4] WinGet was not found. Skipping WinGet update.' - } - } else { - Write-Host '[3] Skipping WinGet' - continue - } + if ($Platform -eq 'Windows') { + Update-WinGetPackage -Skip:$SkipWinGet -AcceptPrompts:$AcceptPrompts @CommonParameters } else { Write-Verbose '[4] Not Windows. Skipping WinGet.' } - #endregion UpdateWinget - #region UpdateLinuxPackages - # Early testing. No progress bar yet. Need to check for admin, different distros, and different package managers. - if ($IsLinux) { - # Determine if we need sudo (not needed if already root) - $NeedsSudo = -not (Test-IsElevated) - - if (Get-Command apt -ErrorAction SilentlyContinue) { - Write-Host '[5] Updating apt packages.' - if ($PSCmdlet.ShouldProcess('apt packages', 'Update and upgrade packages')) { - if ($NeedsSudo) { - & sudo apt update - if ($AcceptPrompts) { - & sudo apt upgrade -y - } else { - & sudo apt upgrade - } - } else { - & apt update - if ($AcceptPrompts) { - & apt upgrade -y - } else { - & apt upgrade - } - } - } - } - if (Get-Command dnf -ErrorAction SilentlyContinue) { - Write-Host '[5] Updating dnf packages.' - if ($PSCmdlet.ShouldProcess('dnf packages', 'Update packages')) { - if ($NeedsSudo) { - if ($AcceptPrompts) { - & sudo dnf update -y - } else { - & sudo dnf update - } - } else { - if ($AcceptPrompts) { - & dnf update -y - } else { - & dnf update - } - } - } - } + if ($Platform -eq 'Linux') { + Update-LinuxPackage -AcceptPrompts:$AcceptPrompts @CommonParameters } else { Write-Verbose '[5] Not Linux. Skipping section.' } - #endregion UpdateLinuxPackages - #region UpdateMacOS - # Early testing. No progress bar yet. Need to check for admin and different package managers. - if ($IsMacOS) { - if ($PSCmdlet.ShouldProcess('macOS software updates', 'List available updates')) { - softwareupdate -l - } - if (Get-Command brew -ErrorAction SilentlyContinue) { - Write-Host '[6] Updating brew packages.' - if ($PSCmdlet.ShouldProcess('Homebrew packages', 'Update and upgrade packages')) { - brew update - brew upgrade - } - } + if ($Platform -eq 'macOS') { + Update-MacOSPackage @CommonParameters } else { Write-Verbose '[6] Not macOS. Skipping section.' } - #endregion UpdateMacOS - #region UpdateChocolatey - # Upgrade Chocolatey packages. Need to check for admin to avoid errors/warnings. - if ((Get-Command choco -ErrorAction SilentlyContinue) -and $IncludeChocolatey) { - # Update the outer progress bar - $PercentCompleteOuter = 90 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Updating Chocolatey Packages' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - Write-Host '[7] Updating Chocolatey Packages' - # Add a function/parameter to run these two feature configuration options, which requires admin to set. - if (Test-IsElevated) { - # Oops, this depends on PSPreworkout being installed or that function otherwise being available. - if ($PSCmdlet.ShouldProcess('Chocolatey features', 'Enable global confirmation and disable non-elevated warnings')) { - choco feature enable -n=allowGlobalConfirmation - choco feature disable --name=showNonElevatedWarnings - } - } else { - Write-Verbose "Run once as an administrator to disable Chocolatey's showNonElevatedWarnings." -Verbose - } - if ($PSCmdlet.ShouldProcess('Chocolatey packages', 'Upgrade Chocolatey and all packages')) { - choco upgrade chocolatey -y --limit-output --accept-license --no-color - choco upgrade all -y --limit-output --accept-license --no-color - } - # Padding to reset host before updating the progress bar. - Write-Host ' ' - } else { - Write-Host '[7] Skipping Chocolatey' + $OptionalCliUpdates = @( + @{ + CommandName = 'gh' + DisplayName = '[7] Updating GitHub CLI Extensions' + CurrentOperation = 'Updating GitHub CLI Extensions' + TargetName = 'GitHub CLI extensions' + ActionName = 'Upgrade all installed extensions' + PercentComplete = 90 + UpdateCommand = { Invoke-GitHubCliExtensionUpgrade } + } + @{ + CommandName = 'copilot' + DisplayName = '[8] Updating GitHub Copilot CLI' + CurrentOperation = 'Updating GitHub Copilot CLI' + TargetName = 'GitHub Copilot CLI' + ActionName = 'Update installed CLI' + PercentComplete = 95 + UpdateCommand = { Invoke-GitHubCopilotCliUpdate } + } + ) + + foreach ($CliUpdate in $OptionalCliUpdates) { + Update-OptionalCli @CliUpdate @CommonParameters } - #endregion UpdateChocolatey - } # end process block + Update-ChocolateyPackage -Include:$IncludeChocolatey @CommonParameters + } end { Write-Host 'Done.' - # Update the outer progress bar - $PercentCompleteOuter = 100 - $ProgressParamOuter = @{ - Id = 0 - Activity = 'Update Everything' - CurrentOperation = 'Finished' - Status = "Progress: $PercentCompleteOuter`% Complete" - PercentComplete = $PercentCompleteOuter - } - Write-Progress @ProgressParamOuter - # Complete the outer progress bar - Write-Progress -Id 0 -Activity 'Update Everything' -Completed + Write-UpdateAllTheThingsProgress -CurrentOperation 'Finished' -PercentComplete 100 + Write-UpdateAllTheThingsProgress -Completed } - } diff --git a/src/Tests/Helpers/Update-AllTheThings.TestHelpers.ps1 b/src/Tests/Helpers/Update-AllTheThings.TestHelpers.ps1 new file mode 100644 index 00000000..2c477c0f --- /dev/null +++ b/src/Tests/Helpers/Update-AllTheThings.TestHelpers.ps1 @@ -0,0 +1,32 @@ +$ModuleRoot = [System.IO.Path]::GetFullPath( + (Join-Path -Path $PSScriptRoot -ChildPath '..\..\PSPreworkout') +) + +$PrivatePaths = @( + 'Test-PSPreworkoutCommand.ps1' + 'Get-PSPreworkoutPlatform.ps1' + 'Write-UpdateAllTheThingsProgress.ps1' + 'Invoke-UpdateNativeCommand.ps1' + 'Get-CimOperatingSystemCaption.ps1' + 'Get-WmiOperatingSystemCaption.ps1' + 'Get-WindowsOperatingSystemCaption.ps1' + 'Read-WinGetServerChoice.ps1' + 'Invoke-WinGetUpgrade.ps1' + 'Invoke-GitHubCliExtensionUpgrade.ps1' + 'Invoke-GitHubCopilotCliUpdate.ps1' + 'Set-UpdateRepositoryTrust.ps1' + 'Update-PowerShellArtifact.ps1' + 'Update-WinGetPackage.ps1' + 'Update-LinuxPackage.ps1' + 'Update-MacOSPackage.ps1' + 'Update-OptionalCli.ps1' + 'Update-ChocolateyPackage.ps1' + 'Write-PSPreworkoutTelemetry.ps1' +) + +foreach ($PrivatePath in $PrivatePaths) { + . (Join-Path -Path $ModuleRoot -ChildPath "Private\$PrivatePath") +} + +. (Join-Path -Path $ModuleRoot -ChildPath 'Public\Test-IsElevated.ps1') +. (Join-Path -Path $ModuleRoot -ChildPath 'Public\Update-AllTheThings.ps1') diff --git a/src/Tests/Invoke-UpdateAllTheThingsCompatibility.ps1 b/src/Tests/Invoke-UpdateAllTheThingsCompatibility.ps1 new file mode 100644 index 00000000..b2f28698 --- /dev/null +++ b/src/Tests/Invoke-UpdateAllTheThingsCompatibility.ps1 @@ -0,0 +1,42 @@ +<# +.SYNOPSIS +Runs the focused Update-AllTheThings compatibility tests. + +.DESCRIPTION +Installs the supported Pester version when necessary and runs the focused test +files used by the cross-platform GitHub Actions matrix. +#> + +[CmdletBinding()] +param() + +$PesterVersion = [version]'5.9.1' +if ($PSVersionTable.PSEdition -eq 'Desktop') { + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +} + +$InstalledPester = Get-Module -ListAvailable -Name Pester | + Where-Object Version -EQ $PesterVersion | + Select-Object -First 1 + +if (-not $InstalledPester) { + Install-Module -Name Pester -RequiredVersion $PesterVersion -Scope CurrentUser -Force -SkipPublisherCheck +} + +Import-Module -Name Pester -RequiredVersion $PesterVersion -Force + +$Configuration = New-PesterConfiguration +$Configuration.Run.Path = @( + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.Contract.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.Cli.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.WinGet.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.Orchestration.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.PackageManagers.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.PowerShell.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.Helpers.Tests.ps1') + (Join-Path -Path $PSScriptRoot -ChildPath 'Unit\Update-AllTheThings.Package.Tests.ps1') +) +$Configuration.Run.Exit = $true +$Configuration.Output.Verbosity = 'Detailed' + +Invoke-Pester -Configuration $Configuration diff --git a/src/Tests/Unit/Update-AllTheThings.Cli.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Cli.Tests.ps1 new file mode 100644 index 00000000..81e3750f --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.Cli.Tests.ps1 @@ -0,0 +1,75 @@ +BeforeDiscovery { + $CliCases = @( + @{ + Name = 'GitHub CLI extensions' + CommandName = 'gh' + UpdateCommand = 'Invoke-GitHubCliExtensionUpgrade' + UpdateScript = { Invoke-GitHubCliExtensionUpgrade } + } + @{ + Name = 'GitHub Copilot CLI' + CommandName = 'copilot' + UpdateCommand = 'Invoke-GitHubCopilotCliUpdate' + UpdateScript = { Invoke-GitHubCopilotCliUpdate } + } + ) +} + +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +Describe 'Update-AllTheThings optional CLI updates' { + BeforeEach { + $script:AvailableCommands = @() + + Mock Test-PSPreworkoutCommand { $Name -in $script:AvailableCommands } + Mock Write-Information + Mock Write-UpdateAllTheThingsProgress + Mock Write-Verbose + Mock Invoke-GitHubCliExtensionUpgrade + Mock Invoke-GitHubCopilotCliUpdate + } + + It 'updates when is available' -ForEach $CliCases { + $script:AvailableCommands = @($CommandName) + $UpdateParameters = @{ + CommandName = $CommandName + DisplayName = "Updating $Name" + CurrentOperation = "Updating $Name" + TargetName = $Name + ActionName = "Update $Name" + PercentComplete = 90 + UpdateCommand = $UpdateScript + Confirm = $false + } + + Update-OptionalCli @UpdateParameters + + Should -Invoke -CommandName $UpdateCommand -Exactly 1 + } + + It 'does not update when is unavailable' -ForEach $CliCases { + Update-OptionalCli -CommandName $CommandName -DisplayName "Updating $Name" ` + -CurrentOperation "Updating $Name" -TargetName $Name -ActionName "Update $Name" ` + -PercentComplete 90 -UpdateCommand $UpdateScript -Confirm:$false + + Should -Invoke -CommandName $UpdateCommand -Exactly 0 + } + + It 'does not run optional CLI updates during WhatIf' { + $script:AvailableCommands = @('gh', 'copilot') + + Update-OptionalCli -CommandName 'gh' -DisplayName 'Updating GitHub CLI extensions' ` + -CurrentOperation 'Updating GitHub CLI extensions' -TargetName 'GitHub CLI extensions' ` + -ActionName 'Update GitHub CLI extensions' -PercentComplete 90 ` + -UpdateCommand { Invoke-GitHubCliExtensionUpgrade } -WhatIf + Update-OptionalCli -CommandName 'copilot' -DisplayName 'Updating GitHub Copilot CLI' ` + -CurrentOperation 'Updating GitHub Copilot CLI' -TargetName 'GitHub Copilot CLI' ` + -ActionName 'Update GitHub Copilot CLI' -PercentComplete 95 ` + -UpdateCommand { Invoke-GitHubCopilotCliUpdate } -WhatIf + + Should -Invoke Invoke-GitHubCliExtensionUpgrade -Exactly 0 + Should -Invoke Invoke-GitHubCopilotCliUpdate -Exactly 0 + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.Contract.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Contract.Tests.ps1 new file mode 100644 index 00000000..18fbc448 --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.Contract.Tests.ps1 @@ -0,0 +1,70 @@ +BeforeDiscovery { + $SwitchParameterCases = @( + @{ Name = 'SkipModules' } + @{ Name = 'SkipScripts' } + @{ Name = 'SkipHelp' } + @{ Name = 'SkipWinGet' } + @{ Name = 'IncludeChocolatey' } + @{ Name = 'AcceptPrompts' } + ) + + $SuppressionCases = @( + @{ Category = 'PSUseSingularNouns' } + @{ Category = 'PSAvoidUsingWriteHost' } + @{ Category = 'PSShouldProcess' } + ) +} +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') + + $Command = Get-Command -Name Update-AllTheThings + $Help = Get-Help -Name Update-AllTheThings -Full +} + +Describe 'Update-AllTheThings command contract' { + It 'defines as an optional switch' -ForEach $SwitchParameterCases { + $Parameter = $Command.Parameters[$Name] + $ParameterAttribute = $Parameter.Attributes | + Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] } + + $Parameter.ParameterType | Should -Be ([switch]) + $ParameterAttribute.Mandatory | Should -Not -Contain $true + } + + It 'exposes the uatt alias' { + $Command.ScriptBlock.Attributes.AliasNames | Should -Contain 'uatt' + } + + It 'supports ShouldProcess' { + $Command.Parameters.Keys | Should -Contain 'WhatIf' + $Command.Parameters.Keys | Should -Contain 'Confirm' + } + + It 'defines SkipChoco as an alias for IncludeChocolatey' { + $Command.Parameters['IncludeChocolatey'].Aliases | Should -Contain 'SkipChoco' + } + + It 'declares the analyzer suppression' -ForEach $SuppressionCases { + $Suppressions = $Command.ScriptBlock.Attributes | + Where-Object { $_ -is [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute] } + + $Suppressions.Category | Should -Contain $Category + } + + It 'documents the command synopsis and examples' { + $Help.Synopsis | Should -Not -BeNullOrEmpty + $Help.Examples.Example | Should -HaveCount 2 + } + + It 'documents cross-platform AcceptPrompts behavior' { + $ParameterHelp = Get-Help -Name Update-AllTheThings -Parameter AcceptPrompts + + $ParameterHelp.Description.Text | Should -Match 'accept prompts.*Linux' + $ParameterHelp.Description.Text | Should -Match 'WinGet.*Windows Server' + } + + It 'documents GitHub CLI updates' { + $Help.Description.Text | Should -Match 'GitHub CLI' + $Help.Description.Text | Should -Match 'GitHub Copilot CLI' + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.Helpers.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Helpers.Tests.ps1 new file mode 100644 index 00000000..e3c6b2cc --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.Helpers.Tests.ps1 @@ -0,0 +1,184 @@ +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +BeforeDiscovery { + $ExternalCommandCases = @( + @{ + Name = 'WinGet' + CommandName = 'Invoke-WinGetUpgrade' + } + @{ + Name = 'GitHub CLI extension' + CommandName = 'Invoke-GitHubCliExtensionUpgrade' + } + @{ + Name = 'GitHub Copilot CLI' + CommandName = 'Invoke-GitHubCopilotCliUpdate' + } + ) +} + +Describe 'Update-AllTheThings compatibility helpers' { + Context 'Get-PSPreworkoutPlatform' { + It 'returns the platform reported by the current PowerShell host' { + $ExpectedPlatform = if ($PSVersionTable.PSEdition -eq 'Desktop') { + 'Windows' + } elseif ($IsWindows) { + 'Windows' + } elseif ($IsLinux) { + 'Linux' + } elseif ($IsMacOS) { + 'macOS' + } else { + 'Unknown' + } + + Get-PSPreworkoutPlatform | Should -Be $ExpectedPlatform + } + } + + Context 'Test-PSPreworkoutCommand' { + BeforeEach { + Mock Get-Command + } + + It 'returns true for an available command' { + Mock Get-Command { @{ Name = 'Get-Command' } } + + Test-PSPreworkoutCommand -Name 'Get-Command' | Should -BeTrue + } + + It 'returns false for an unavailable command' { + Test-PSPreworkoutCommand -Name 'PSPreworkout.Command.That.Does.Not.Exist' | Should -BeFalse + } + } + + Context 'Get-WindowsOperatingSystemCaption' { + BeforeEach { + $script:AvailableCommands = @() + Mock Test-PSPreworkoutCommand { $Name -in $script:AvailableCommands } + Mock Get-CimOperatingSystemCaption + Mock Get-WmiOperatingSystemCaption + Mock Write-Verbose + } + + It 'uses CIM when it is available' { + $script:AvailableCommands = @('Get-CimInstance') + Mock Get-CimOperatingSystemCaption { 'Windows 11 Pro' } + + Get-WindowsOperatingSystemCaption | Should -Be 'Windows 11 Pro' + + Should -Invoke Get-CimOperatingSystemCaption -Exactly 1 + Should -Invoke Get-WmiOperatingSystemCaption -Exactly 0 + } + + It 'falls back to WMI when CIM fails' { + $script:AvailableCommands = @('Get-CimInstance', 'Get-WmiObject') + Mock Get-CimOperatingSystemCaption { throw 'CIM failure' } + Mock Get-WmiOperatingSystemCaption { 'Windows Server 2025 Datacenter' } + + Get-WindowsOperatingSystemCaption | Should -Be 'Windows Server 2025 Datacenter' + + Should -Invoke Get-CimOperatingSystemCaption -Exactly 1 + Should -Invoke Get-WmiOperatingSystemCaption -Exactly 1 + } + + It 'returns no caption when neither API is available' { + Get-WindowsOperatingSystemCaption | Should -BeNullOrEmpty + + Should -Invoke Get-CimOperatingSystemCaption -Exactly 0 + Should -Invoke Get-WmiOperatingSystemCaption -Exactly 0 + } + } + + Context 'operating-system query wrappers' { + It 'returns the CIM query result' { + Get-CimOperatingSystemCaption -Query { 'Windows 11 Pro' } | + Should -Be 'Windows 11 Pro' + } + + It 'returns the WMI query result' { + Get-WmiOperatingSystemCaption -Query { 'Windows Server 2025 Datacenter' } | + Should -Be 'Windows Server 2025 Datacenter' + } + } + + Context 'Read-WinGetServerChoice' { + It 'defaults to declining the update' { + $HostUserInterface = [PSCustomObject]@{} + $HostUserInterface | Add-Member -MemberType ScriptMethod -Name PromptForChoice -Value { + param($Title, $Message, $Options, $DefaultChoice) + + $Title | Should -Be 'Windows Server OS Found' + $Message | Should -Match 'winget upgrade' + $Options | Should -HaveCount 2 + return $DefaultChoice + } + + Read-WinGetServerChoice -HostUserInterface $HostUserInterface | Should -Be 1 + } + } + + Context 'external command wrappers' { + It 'completes the update when the command succeeds' -ForEach $ExternalCommandCases { + { & $CommandName -Command { 0 } } | Should -Not -Throw + } + + It 'throws for a failed update' -ForEach $ExternalCommandCases { + { & $CommandName -Command { 23 } } | Should -Throw '*exit code 23*' + } + } + + Context 'Invoke-UpdateNativeCommand' { + It 'passes the command name and arguments to the invocation seam' { + $script:InvokedCommand = $null + $script:InvokedArguments = $null + $Command = { + param($CommandName, $CommandArguments) + + $script:InvokedCommand = $CommandName + $script:InvokedArguments = $CommandArguments + return 0 + } + + Invoke-UpdateNativeCommand -Name 'package-manager' -ArgumentList 'update', '-y' ` + -FailureMessage 'Package update' -Command $Command + + $script:InvokedCommand | Should -Be 'package-manager' + $script:InvokedArguments | Should -Be @('update', '-y') + } + + It 'throws with context when the native command fails' { + { + Invoke-UpdateNativeCommand -Name 'package-manager' -FailureMessage 'Package update' ` + -Command { 17 } + } | Should -Throw 'Package update failed with exit code 17.' + } + } + + Context 'Write-UpdateAllTheThingsProgress' { + BeforeEach { + Mock Write-Progress + } + + It 'writes a parent progress record' { + Write-UpdateAllTheThingsProgress -CurrentOperation 'Testing progress' -PercentComplete 42 + + Should -Invoke Write-Progress -Exactly 1 -ParameterFilter { + $Id -eq 0 -and + $Activity -eq 'Update Everything' -and + $CurrentOperation -eq 'Testing progress' -and + $PercentComplete -eq 42 + } + } + + It 'completes the parent progress record' { + Write-UpdateAllTheThingsProgress -Completed + + Should -Invoke Write-Progress -Exactly 1 -ParameterFilter { + $Id -eq 0 -and $Completed + } + } + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.Orchestration.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Orchestration.Tests.ps1 new file mode 100644 index 00000000..ac693e8f --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.Orchestration.Tests.ps1 @@ -0,0 +1,82 @@ +BeforeDiscovery { + $PlatformCases = @( + @{ + Platform = 'Windows' + ExpectedCommand = 'Update-WinGetPackage' + } + @{ + Platform = 'Linux' + ExpectedCommand = 'Update-LinuxPackage' + } + @{ + Platform = 'macOS' + ExpectedCommand = 'Update-MacOSPackage' + } + ) +} + +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +Describe 'Update-AllTheThings orchestration' { + BeforeEach { + Mock Test-PSPreworkoutCommand { $false } + Mock Get-PSPreworkoutPlatform { 'Unknown' } + Mock Set-UpdateRepositoryTrust + Mock Update-PowerShellArtifact + Mock Update-WinGetPackage + Mock Update-LinuxPackage + Mock Update-MacOSPackage + Mock Update-OptionalCli + Mock Update-ChocolateyPackage + Mock Write-Host + Mock Write-Verbose + Mock Write-UpdateAllTheThingsProgress + } + + It 'runs the shared update stages once' { + Update-AllTheThings -SkipModules -SkipScripts -SkipHelp -SkipWinGet + + Should -Invoke Set-UpdateRepositoryTrust -Exactly 1 + Should -Invoke Update-PowerShellArtifact -Exactly 1 -ParameterFilter { + $SkipModules -and $SkipScripts -and $SkipHelp + } + Should -Invoke Update-OptionalCli -Exactly 2 + Should -Invoke Update-ChocolateyPackage -Exactly 1 + } + + It 'runs only the platform updater' -ForEach $PlatformCases { + Mock Get-PSPreworkoutPlatform { $Platform } + + Update-AllTheThings -SkipModules -SkipScripts -SkipHelp -Confirm:$false + + Should -Invoke -CommandName $ExpectedCommand -Exactly 1 + Should -Invoke Update-WinGetPackage -Exactly ([int]($Platform -eq 'Windows')) + Should -Invoke Update-LinuxPackage -Exactly ([int]($Platform -eq 'Linux')) + Should -Invoke Update-MacOSPackage -Exactly ([int]($Platform -eq 'macOS')) + } + + It 'forwards package-manager options to their update stages' { + Mock Get-PSPreworkoutPlatform { 'Windows' } + + Update-AllTheThings -SkipModules -SkipScripts -SkipHelp -SkipWinGet ` + -AcceptPrompts -IncludeChocolatey -Confirm:$false + + Should -Invoke Update-WinGetPackage -Exactly 1 -ParameterFilter { + $Skip -and $AcceptPrompts -and (-not $Confirm) + } + Should -Invoke Update-ChocolateyPackage -Exactly 1 -ParameterFilter { + $Include -and (-not $Confirm) + } + } + + It 'forwards WhatIf to update stages' { + Update-AllTheThings -SkipModules -SkipScripts -SkipHelp -SkipWinGet -WhatIf + + Should -Invoke Set-UpdateRepositoryTrust -Exactly 1 -ParameterFilter { $WhatIf } + Should -Invoke Update-PowerShellArtifact -Exactly 1 -ParameterFilter { $WhatIf } + Should -Invoke Update-OptionalCli -Exactly 2 -ParameterFilter { $WhatIf } + Should -Invoke Update-ChocolateyPackage -Exactly 1 -ParameterFilter { $WhatIf } + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.Package.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Package.Tests.ps1 new file mode 100644 index 00000000..54560c88 --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.Package.Tests.ps1 @@ -0,0 +1,36 @@ +BeforeAll { + $RepositoryRoot = [System.IO.Path]::GetFullPath( + (Join-Path -Path $PSScriptRoot -ChildPath '..\..\..') + ) + $BuildScriptPath = Join-Path -Path $RepositoryRoot -ChildPath 'Scripts\Update-AllTheThings_Build.ps1' + $PackagedScriptPath = Join-Path -Path $RepositoryRoot -ChildPath 'Scripts\Update-AllTheThings.ps1' +} + +Describe 'Update-AllTheThings packaged script' { + It 'matches the generated source artifact byte for byte' { + $GeneratedScriptPath = Join-Path -Path $TestDrive -ChildPath 'Update-AllTheThings.ps1' + + & $BuildScriptPath -OutputPath $GeneratedScriptPath + + $GeneratedBytes = [System.IO.File]::ReadAllBytes($GeneratedScriptPath) + $PackagedBytes = [System.IO.File]::ReadAllBytes($PackagedScriptPath) + + [Convert]::ToBase64String($GeneratedBytes) | + Should -BeExactly ([Convert]::ToBase64String($PackagedBytes)) + } + + It 'loads in an isolated PowerShell process' { + $SmokeTestPath = Join-Path -Path $TestDrive -ChildPath 'SmokeTest.ps1' + $EscapedPackagePath = $PackagedScriptPath.Replace("'", "''") + @" +. '$EscapedPackagePath' +Get-Command -Name Update-AllTheThings -ErrorAction Stop | Out-Null +Test-IsElevated | Out-Null +"@ | Set-Content -LiteralPath $SmokeTestPath -Encoding utf8 + + $PowerShellPath = (Get-Process -Id $PID).Path + & $PowerShellPath -NoLogo -NoProfile -NonInteractive -File $SmokeTestPath + + $LASTEXITCODE | Should -Be 0 + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.PackageManagers.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.PackageManagers.Tests.ps1 new file mode 100644 index 00000000..4b917b68 --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.PackageManagers.Tests.ps1 @@ -0,0 +1,100 @@ +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +Describe 'Update-AllTheThings package-manager helpers' { + BeforeEach { + $script:AvailableCommands = @() + + Mock Test-PSPreworkoutCommand { $Name -in $script:AvailableCommands } + Mock Test-IsElevated { $true } + Mock Invoke-UpdateNativeCommand + Mock Write-Information + Mock Write-Verbose + Mock Write-Warning + Mock Write-UpdateAllTheThingsProgress + } + + Context 'Linux package updates' { + It 'updates apt non-interactively without sudo when elevated' { + $script:AvailableCommands = @('apt') + + Update-LinuxPackage -AcceptPrompts -Confirm:$false + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'apt' -and ($ArgumentList -join ' ') -eq 'update' + } + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'apt' -and ($ArgumentList -join ' ') -eq 'upgrade -y' + } + } + + It 'uses sudo for dnf when not elevated' { + $script:AvailableCommands = @('dnf') + Mock Test-IsElevated { $false } + + Update-LinuxPackage -Confirm:$false + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'sudo' -and ($ArgumentList -join ' ') -eq 'dnf update' + } + } + + It 'does not invoke package managers during WhatIf' { + $script:AvailableCommands = @('apt', 'dnf') + + Update-LinuxPackage -WhatIf + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 0 + } + + It 'does not inspect elevation when no supported package manager is installed' { + Update-LinuxPackage + + Should -Invoke Test-IsElevated -Exactly 0 + Should -Invoke Invoke-UpdateNativeCommand -Exactly 0 + } + } + + Context 'macOS package updates' { + It 'updates system software and Homebrew' { + $script:AvailableCommands = @('brew') + + Update-MacOSPackage -Confirm:$false + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'softwareupdate' -and ($ArgumentList -join ' ') -eq '-l' + } + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'brew' -and ($ArgumentList -join ' ') -eq 'update' + } + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + $Name -eq 'brew' -and ($ArgumentList -join ' ') -eq 'upgrade' + } + } + } + + Context 'Chocolatey package updates' { + It 'updates Chocolatey features and packages when included and elevated' { + $script:AvailableCommands = @('choco') + + Update-ChocolateyPackage -Include -Confirm:$false + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 4 + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + ($ArgumentList -join ' ') -eq 'upgrade chocolatey -y --limit-output --accept-license --no-color' + } + Should -Invoke Invoke-UpdateNativeCommand -Exactly 1 -ParameterFilter { + ($ArgumentList -join ' ') -eq 'upgrade all -y --limit-output --accept-license --no-color' + } + } + + It 'does not invoke Chocolatey when it is not included' { + $script:AvailableCommands = @('choco') + + Update-ChocolateyPackage + + Should -Invoke Invoke-UpdateNativeCommand -Exactly 0 + } + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.PowerShell.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.PowerShell.Tests.ps1 new file mode 100644 index 00000000..3ec7d9fb --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.PowerShell.Tests.ps1 @@ -0,0 +1,54 @@ +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +Describe 'Update-AllTheThings PowerShell updates' { + BeforeEach { + $script:AvailableCommands = @('Get-InstalledModule', 'Update-Script') + + Mock Test-PSPreworkoutCommand { $Name -in $script:AvailableCommands } + Mock Get-InstalledModule { + @( + [PSCustomObject]@{ Name = 'StableModule'; Version = [version]'1.2.3' } + [PSCustomObject]@{ Name = 'PreviewModule'; Version = '2.0.0-preview1' } + ) + } + Mock Update-Module + Mock Update-Script + Mock Update-Help + Mock Get-Culture { [cultureinfo]'en-US' } + Mock Write-Information + Mock Write-Warning + Mock Write-Verbose + Mock Write-Progress + Mock Write-UpdateAllTheThingsProgress + } + + It 'updates stable modules, scripts, and help' { + Update-PowerShellArtifact -Confirm:$false + + Should -Invoke Update-Module -Exactly 1 -ParameterFilter { $Name -eq 'StableModule' } + Should -Invoke Update-Module -Exactly 0 -ParameterFilter { $Name -eq 'PreviewModule' } + Should -Invoke Update-Script -Exactly 1 + Should -Invoke Update-Help -Exactly 1 + } + + It 'skips every PowerShell update when requested' { + Update-PowerShellArtifact -SkipModules -SkipScripts -SkipHelp + + Should -Invoke Get-InstalledModule -Exactly 0 + Should -Invoke Update-Module -Exactly 0 + Should -Invoke Update-Script -Exactly 0 + Should -Invoke Update-Help -Exactly 0 + } + + It 'skips unavailable module and script tooling with explicit warnings' { + $script:AvailableCommands = @() + + Update-PowerShellArtifact -SkipHelp + + Should -Invoke Write-Warning -Exactly 2 + Should -Invoke Update-Module -Exactly 0 + Should -Invoke Update-Script -Exactly 0 + } +} diff --git a/src/Tests/Unit/Update-AllTheThings.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.Tests.ps1 deleted file mode 100644 index 2dec51c2..00000000 --- a/src/Tests/Unit/Update-AllTheThings.Tests.ps1 +++ /dev/null @@ -1,112 +0,0 @@ -BeforeAll { - # Import the module or function under test - $ModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent - $PublicPath = Join-Path -Path $ModulePath -ChildPath 'PSPreworkout\Public' - . (Join-Path -Path $PublicPath -ChildPath 'Update-AllTheThings.ps1') -} - -Describe 'Update-AllTheThings' { - Context 'Parameter Validation' { - It 'Should have the correct parameters defined' { - $Function = Get-Command Update-AllTheThings - $Function.Parameters.Keys | Should -Contain 'SkipModules' - $Function.Parameters.Keys | Should -Contain 'SkipScripts' - $Function.Parameters.Keys | Should -Contain 'SkipHelp' - $Function.Parameters.Keys | Should -Contain 'SkipWinGet' - $Function.Parameters.Keys | Should -Contain 'IncludeChocolatey' - $Function.Parameters.Keys | Should -Contain 'AcceptPrompts' - } - - It 'Should have the correct alias' { - $Function = Get-Command Update-AllTheThings - $Function.Definition | Should -Match '\[Alias\(''uatt''\)\]' - } - - It 'Should have AcceptPrompts parameter as a switch' { - $Function = Get-Command Update-AllTheThings - $AcceptPromptsParam = $Function.Parameters['AcceptPrompts'] - $AcceptPromptsParam.ParameterType.Name | Should -Be 'SwitchParameter' - } - - It 'Should have AcceptPrompts parameter set as optional' { - $Function = Get-Command Update-AllTheThings - $AcceptPromptsParam = $Function.Parameters['AcceptPrompts'] - $AcceptPromptsParam.Attributes.Mandatory | Should -Not -Contain $true - } - - It 'Should support ShouldProcess' { - $Function = Get-Command Update-AllTheThings - $Function.Parameters.Keys | Should -Contain 'WhatIf' - $Function.Parameters.Keys | Should -Contain 'Confirm' - } - - It 'Should have IncludeChocolatey parameter with SkipChoco alias' { - $Function = Get-Command Update-AllTheThings - $IncludeChocolateyParam = $Function.Parameters['IncludeChocolatey'] - $IncludeChocolateyParam.Aliases | Should -Contain 'SkipChoco' - } - } - - Context 'Help Documentation' { - It 'Should have help documentation' { - $Help = Get-Help Update-AllTheThings - $Help | Should -Not -BeNullOrEmpty - $Help.Synopsis | Should -Not -BeNullOrEmpty - } - - It 'Should have AcceptPrompts parameter documented in help' { - $Help = Get-Help Update-AllTheThings -Parameter AcceptPrompts - $Help | Should -Not -BeNullOrEmpty - $Help.Description.Text | Should -Match 'accept prompts.*Linux' - } - - It 'Should have examples in help documentation' { - $Help = Get-Help Update-AllTheThings -Examples - $Help.Examples.Example | Should -Not -BeNullOrEmpty - $Help.Examples.Example.Count | Should -BeGreaterOrEqual 2 - } - - It 'Should have an example demonstrating AcceptPrompts usage' { - $Help = Get-Help Update-AllTheThings -Examples - $ExamplesText = $Help.Examples.Example.Code -join ' ' - $ExamplesText | Should -Match '-AcceptPrompts' - } - } - - Context 'Function Definition' { - It 'Should have CmdletBinding attribute' { - $Function = Get-Command Update-AllTheThings - $Function.CmdletBinding | Should -Not -BeNullOrEmpty - } - - It 'Should have PSUseSingularNouns suppression attribute' { - $Function = Get-Command Update-AllTheThings - $Function.ScriptBlock.Attributes.TypeId.Name | Should -Contain 'SuppressMessageAttribute' - } - - It 'Should have PSAvoidUsingWriteHost suppression attribute' { - $Function = Get-Command Update-AllTheThings - $Function.ScriptBlock.Attributes.TypeId.Name | Should -Contain 'SuppressMessageAttribute' - } - } - - Context 'Parameter Types' { - It 'Should have all Skip parameters as switch type' { - $Function = Get-Command Update-AllTheThings - $Function.Parameters['SkipModules'].ParameterType.Name | Should -Be 'SwitchParameter' - $Function.Parameters['SkipScripts'].ParameterType.Name | Should -Be 'SwitchParameter' - $Function.Parameters['SkipHelp'].ParameterType.Name | Should -Be 'SwitchParameter' - $Function.Parameters['SkipWinGet'].ParameterType.Name | Should -Be 'SwitchParameter' - } - - It 'Should have IncludeChocolatey parameter as switch type' { - $Function = Get-Command Update-AllTheThings - $Function.Parameters['IncludeChocolatey'].ParameterType.Name | Should -Be 'SwitchParameter' - } - - It 'Should have AcceptPrompts parameter as switch type' { - $Function = Get-Command Update-AllTheThings - $Function.Parameters['AcceptPrompts'].ParameterType.Name | Should -Be 'SwitchParameter' - } - } -} diff --git a/src/Tests/Unit/Update-AllTheThings.WinGet.Tests.ps1 b/src/Tests/Unit/Update-AllTheThings.WinGet.Tests.ps1 new file mode 100644 index 00000000..83bd72c9 --- /dev/null +++ b/src/Tests/Unit/Update-AllTheThings.WinGet.Tests.ps1 @@ -0,0 +1,103 @@ +BeforeDiscovery { + $NonInteractiveConsentCases = @( + @{ + Name = 'WhatIf' + Additional = @{ WhatIf = $true } + ExpectedUpdates = 0 + } + @{ + Name = 'Confirm false' + Additional = @{ Confirm = $false } + ExpectedUpdates = 1 + } + @{ + Name = 'AcceptPrompts' + Additional = @{ AcceptPrompts = $true } + ExpectedUpdates = 1 + } + ) +} + +BeforeAll { + . (Join-Path -Path $PSScriptRoot -ChildPath '..\Helpers\Update-AllTheThings.TestHelpers.ps1') +} + +Describe 'Update-AllTheThings WinGet behavior' { + BeforeEach { + $script:AvailableCommands = @('winget') + + Mock Test-PSPreworkoutCommand { $Name -in $script:AvailableCommands } + Mock Get-WindowsOperatingSystemCaption { 'Windows Server 2025 Datacenter' } + Mock Read-WinGetServerChoice { 0 } + Mock Invoke-WinGetUpgrade + Mock Write-Information + Mock Write-UpdateAllTheThingsProgress + Mock Write-Verbose + Mock Write-Warning + } + + It 'updates packages when the Windows Server prompt is accepted' { + Update-WinGetPackage + + Should -Invoke Read-WinGetServerChoice -Exactly 1 + Should -Invoke Invoke-WinGetUpgrade -Exactly 1 + } + + It 'skips packages when the Windows Server prompt is declined' { + Mock Read-WinGetServerChoice { 1 } + + Update-WinGetPackage + + Should -Invoke Read-WinGetServerChoice -Exactly 1 + Should -Invoke Invoke-WinGetUpgrade -Exactly 0 + } + + It 'does not prompt with ' -ForEach $NonInteractiveConsentCases { + $Parameters = @{} + foreach ($Entry in $Additional.GetEnumerator()) { + $Parameters[$Entry.Key] = $Entry.Value + } + + Update-WinGetPackage @Parameters + + Should -Invoke Read-WinGetServerChoice -Exactly 0 + Should -Invoke Invoke-WinGetUpgrade -Exactly $ExpectedUpdates + } + + It 'does not prompt on a Windows client' { + Mock Get-WindowsOperatingSystemCaption { 'Microsoft Windows 11 Pro' } + + Update-WinGetPackage + + Should -Invoke Read-WinGetServerChoice -Exactly 0 + Should -Invoke Invoke-WinGetUpgrade -Exactly 1 + } + + It 'fails closed when the Windows caption cannot be determined' { + Mock Get-WindowsOperatingSystemCaption + + Update-WinGetPackage + + Should -Invoke Write-Warning -Exactly 1 -ParameterFilter { + $Message -match 'Unable to determine the Windows operating system caption' + } + Should -Invoke Invoke-WinGetUpgrade -Exactly 0 + } + + It 'does not inspect Windows when WinGet is skipped explicitly' { + Update-WinGetPackage -Skip + + Should -Invoke Get-WindowsOperatingSystemCaption -Exactly 0 + Should -Invoke Read-WinGetServerChoice -Exactly 0 + Should -Invoke Invoke-WinGetUpgrade -Exactly 0 + } + + It 'skips WinGet when the command is unavailable' { + $script:AvailableCommands = @() + + Update-WinGetPackage + + Should -Invoke Get-WindowsOperatingSystemCaption -Exactly 0 + Should -Invoke Invoke-WinGetUpgrade -Exactly 0 + } +} diff --git a/src/actions_bootstrap.ps1 b/src/actions_bootstrap.ps1 index 7adefe8d..526443fe 100644 --- a/src/actions_bootstrap.ps1 +++ b/src/actions_bootstrap.ps1 @@ -10,8 +10,8 @@ Set-PSRepository -Name PSGallery -InstallationPolicy Trusted $modulesToInstall = New-Object System.Collections.Generic.List[object] # https://github.com/pester/Pester [void]$modulesToInstall.Add(([PSCustomObject]@{ - ModuleName = 'Pester' - #ModuleVersion = '5.6.1' + ModuleName = 'Pester' + ModuleVersion = '5.9.1' })) # https://github.com/nightroman/Invoke-Build [void]$modulesToInstall.Add(([PSCustomObject]@{ @@ -48,7 +48,14 @@ foreach ($module in $modulesToInstall) { } else { Install-Module @installSplat } - Import-Module -Name $module.ModuleName -ErrorAction Stop + $importSplat = @{ + Name = $module.ModuleName + ErrorAction = 'Stop' + } + if ($module.ModuleVersion) { + $importSplat.RequiredVersion = $module.ModuleVersion + } + Import-Module @importSplat ' - Successfully installed {0}' -f $module.ModuleName } catch { $message = 'Failed to install {0}' -f $module.ModuleName