#requires -Version 5.1 [CmdletBinding()] param( [string]$Repository, [ValidatePattern('^[a-z0-9][a-z0-9-]*$')][string]$Machine, [ValidatePattern('^[A-Za-z0-9._/-]+$')][string]$Branch = 'main', [string]$Checkout = (Join-Path $env:LOCALAPPDATA 'ConfigCentral\repository'), [switch]$SkipApply, [switch]$PreserveLocalConfigs, [switch]$RepairWinGetOnly ) # Kept identical in standalone entrypoints; verified by Output.Tests.ps1. function Write-ConfigCentralMessage { param([string]$Message, [ValidateSet('Info', 'Success', 'Warning', 'Error')][string]$Level = 'Info') $color = switch ($Level) { 'Success' { 'Green' } 'Warning' { 'Yellow' } 'Error' { 'Red' } default { 'Cyan' } } $redirected = if ($Level -eq 'Error') { [Console]::IsErrorRedirected } else { [Console]::IsOutputRedirected } $useColor = -not $redirected -and $null -eq [Environment]::GetEnvironmentVariable('NO_COLOR') if ($Level -eq 'Error') { $previous = $null try { if ($useColor) { $previous = [Console]::ForegroundColor; [Console]::ForegroundColor = $color } [Console]::Error.WriteLine($Message) } finally { if ($null -ne $previous) { [Console]::ForegroundColor = $previous } } } elseif ($useColor) { Write-Host $Message -ForegroundColor $color } else { Write-Host $Message } } try { Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $script:BootstrapScriptPath = if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { [string]$MyInvocation.MyCommand.Path } else { $null } if ([string]::IsNullOrWhiteSpace($script:BootstrapScriptPath)) { throw 'bootstrap.ps1 must be downloaded and run as a file so administrator relaunch can work.' } function Test-Administrator { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } function Invoke-BootstrapWingetInstall { param([Parameter(Mandatory = $true)][string]$Id) $installerArguments = @('install', '--id', $Id, '--exact', '--source', 'winget', '--silent', '--disable-interactivity', '--accept-package-agreements', '--accept-source-agreements', '--scope', 'machine') # Require the self-contained MSI instead of following WinGet's MSIX default. if ($Id -eq 'Microsoft.PowerShell') { $installerArguments += @('--installer-type', 'wix') } & winget.exe @installerArguments if ($LASTEXITCODE -ne 0) { throw "WinGet failed to install '$Id' (exit $LASTEXITCODE)." } } function Find-PowerShell7Path { if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) { $installedPath = Join-Path $env:ProgramFiles 'PowerShell\7\pwsh.exe' if (Test-Path -LiteralPath $installedPath -PathType Leaf) { return $installedPath } } $command = Get-Command pwsh.exe -CommandType Application -ErrorAction SilentlyContinue if ($command) { return $command.Source } return $null } function Assert-BootstrapPowerShell { param([Parameter(Mandatory = $true)][string]$Path) # Preserve native startup diagnostics (including missing .NET) under PS 5.1. $previousPreference = $ErrorActionPreference try { $ErrorActionPreference = 'Continue' $diagnostics = & $Path -NoLogo -NoProfile -NonInteractive -Command 'if ($PSVersionTable.PSVersion.Major -lt 7) { exit 1 }; Write-Output "ConfigCentral.PowerShell7.Ready"; exit 0' 2>&1 $code = $LASTEXITCODE } finally { $ErrorActionPreference = $previousPreference } if ($code -ne 0 -or @($diagnostics) -notcontains 'ConfigCentral.PowerShell7.Ready') { throw "PowerShell at '$Path' could not start (exit $code): $($diagnostics -join [Environment]::NewLine). Repair that installation or install the official PowerShell 7 MSI, then rerun setup." } } function Invoke-BootstrapApply { param( [Parameter(Mandatory = $true)][string]$PowerShell, [Parameter(Mandatory = $true)][string[]]$Arguments, [Parameter(Mandatory = $true)][string]$Machine ) $outputPath = [System.IO.Path]::GetTempFileName() $errorPath = [System.IO.Path]::GetTempFileName() $process = $null $stopwatch = [Diagnostics.Stopwatch]::StartNew() $animate = -not [Console]::IsOutputRedirected try { $quotedArguments = @($Arguments | ForEach-Object { if ($_ -match '"') { throw 'Bootstrap apply arguments cannot contain quotation marks.' } '"' + $_ + '"' }) Write-ConfigCentralMessage -Message "Applying software and configs for '$Machine'. This can take several minutes..." $process = Start-Process -FilePath $PowerShell -ArgumentList $quotedArguments -PassThru -NoNewWindow -RedirectStandardOutput $outputPath -RedirectStandardError $errorPath $frames = @('|', '/', '-', '\') $frame = 0 while (-not $process.WaitForExit(125)) { if ($animate) { Write-Host -NoNewline ("`r{0} Working... {1}s" -f $frames[$frame % $frames.Count], [int]$stopwatch.Elapsed.TotalSeconds) $frame++ } } if ($animate) { Write-Host -NoNewline ("`r{0}`r" -f (' ' * 48)) } $output = Get-Content -LiteralPath $outputPath -Raw -ErrorAction SilentlyContinue $errors = Get-Content -LiteralPath $errorPath -Raw -ErrorAction SilentlyContinue if ($output) { [Console]::Out.Write($output) } if ($errors) { [Console]::Error.Write($errors) } return $process.ExitCode } finally { $stopwatch.Stop() if ($process -and -not $process.HasExited) { $process.WaitForExit() } Remove-Item -LiteralPath $outputPath, $errorPath -Force -ErrorAction SilentlyContinue } } function Find-GitPath { $command = Get-Command git.exe -ErrorAction SilentlyContinue if ($command) { return $command.Source } $candidates = @() if (-not [string]::IsNullOrWhiteSpace($env:ProgramFiles)) { $candidates += (Join-Path $env:ProgramFiles 'Git\cmd\git.exe') $candidates += (Join-Path $env:ProgramFiles 'Git\bin\git.exe') } $programFilesX86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)') if (-not [string]::IsNullOrWhiteSpace($programFilesX86)) { $candidates += (Join-Path $programFilesX86 'Git\cmd\git.exe') } if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe') } foreach ($candidate in $candidates) { if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate } } return $null } function Update-BootstrapProcessPath { $pathValues = @( [Environment]::GetEnvironmentVariable('Path', 'Machine'), [Environment]::GetEnvironmentVariable('Path', 'User'), $env:Path ) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } $env:Path = $pathValues -join ';' } function Ensure-WinGet { if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } try { Add-AppxPackage -RegisterByFamilyName -MainPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe -ErrorAction Stop } catch { Write-Verbose "Desktop App Installer registration did not restore WinGet: $($_.Exception.Message)" } if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } if (-not (Test-Administrator)) { $arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$script:BootstrapScriptPath`" -RepairWinGetOnly" $repair = Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru if ($repair.ExitCode -ne 0) { throw "Elevated WinGet repair failed (exit $($repair.ExitCode))." } if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { $windowsApps = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps' if (($env:Path -split ';') -notcontains $windowsApps) { $env:Path = "$env:Path;$windowsApps" } } if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { throw 'WinGet was repaired but is unavailable in the current user session.' } return } if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Force -Scope AllUsers | Out-Null } Install-Module -Name Microsoft.WinGet.Client -Repository PSGallery -Force -Scope AllUsers -AllowClobber Repair-WinGetPackageManager -AllUsers if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { throw 'WinGet repair completed but winget.exe remains unavailable.' } } if ($RepairWinGetOnly) { if (-not (Test-Administrator)) { throw 'WinGet repair requires administrator rights.' } if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Force -Scope AllUsers | Out-Null } Install-Module -Name Microsoft.WinGet.Client -Repository PSGallery -Force -Scope AllUsers -AllowClobber Repair-WinGetPackageManager -AllUsers exit 0 } if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Config Central bootstrap runs only on Windows.' } if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA) -or [string]::IsNullOrWhiteSpace($env:USERPROFILE)) { throw 'The interactive user profile is unavailable.' } if ([string]::IsNullOrWhiteSpace($Repository) -or [string]::IsNullOrWhiteSpace($Machine)) { throw 'Bootstrap requires -Repository and -Machine.' } Write-Host 'Checking WinGet...' Ensure-WinGet if (-not (Find-GitPath)) { Invoke-BootstrapWingetInstall -Id 'Git.Git' } if (-not (Find-PowerShell7Path)) { Invoke-BootstrapWingetInstall -Id 'Microsoft.PowerShell' } Update-BootstrapProcessPath $git = Find-GitPath if (-not $git) { throw 'Git was installed but git.exe could not be located.' } $powerShell7 = Find-PowerShell7Path if (-not $powerShell7) { throw 'PowerShell 7 was installed but pwsh.exe could not be located.' } Assert-BootstrapPowerShell -Path $powerShell7 if (Test-Path -LiteralPath (Join-Path $Checkout '.git')) { Push-Location $Checkout try { $dirty = & $git status --porcelain=v1 --untracked-files=all if ($LASTEXITCODE -ne 0) { throw 'Unable to inspect the existing checkout.' } if ($dirty) { throw "Existing checkout '$Checkout' has local changes; bootstrap will not replace them." } $origin = (& $git remote get-url origin).Trim() if ($origin -ne $Repository) { throw "Existing checkout origin '$origin' does not match '$Repository'." } & $git fetch --prune origin $Branch if ($LASTEXITCODE -ne 0) { throw 'Unable to fetch the configured branch.' } & $git checkout -B $Branch "origin/$Branch" if ($LASTEXITCODE -ne 0) { throw 'Unable to update the bootstrap checkout.' } } finally { Pop-Location } } else { $parent = Split-Path -Parent $Checkout New-Item -ItemType Directory -Path $parent -Force | Out-Null & $git clone --branch $Branch --single-branch $Repository $Checkout if ($LASTEXITCODE -ne 0) { throw "Unable to clone '$Repository'." } } $dataRoot = Join-Path $env:LOCALAPPDATA 'ConfigCentral' New-Item -ItemType Directory -Path $dataRoot -Force | Out-Null $settings = [ordered]@{ repositoryUrl = $Repository branch = $Branch machine = $Machine checkout = $Checkout userPaths = [ordered]@{ APPDATA = $env:APPDATA LOCALAPPDATA = $env:LOCALAPPDATA USERPROFILE = $env:USERPROFILE PROGRAMDATA = $env:PROGRAMDATA SYSTEMROOT = $env:SYSTEMROOT } } $settings | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $dataRoot 'settings.json') -Encoding UTF8 $launcherDirectory = Join-Path $env:LOCALAPPDATA 'ConfigCentral\bin' New-Item -ItemType Directory -Path $launcherDirectory -Force | Out-Null $launcherPath = Join-Path $launcherDirectory 'cc.cmd' $launcherContent = "@echo off`r`n`"$powerShell7`" -NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$Checkout\cc.ps1`" %*`r`n" [System.IO.File]::WriteAllText($launcherPath, $launcherContent, [Text.Encoding]::ASCII) $userPath = [Environment]::GetEnvironmentVariable('Path', 'User') if (($userPath -split ';') -notcontains $launcherDirectory) { [Environment]::SetEnvironmentVariable('Path', (($userPath.TrimEnd(';') + ';' + $launcherDirectory).TrimStart(';')), 'User') $env:Path = "$env:Path;$launcherDirectory" } Write-ConfigCentralMessage -Level Success -Message "Config Central configured for '$Machine'." if (-not $SkipApply) { $applyArguments = @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $Checkout 'cc.ps1'), 'apply', '-Machine', $Machine, '-DataRoot', $dataRoot, '-RepositoryRoot', $Checkout) if (-not $PreserveLocalConfigs) { $applyArguments += '-ForceConfigs' } $applyExitCode = Invoke-BootstrapApply -PowerShell $powerShell7 -Arguments $applyArguments -Machine $Machine exit $applyExitCode } $global:LASTEXITCODE = 0 } catch { Write-ConfigCentralMessage -Level Error -Message "Setup prerequisites could not complete: $($_.Exception.Message)" Write-Host 'Correct the reported issue and rerun the command. Completed changes are kept.' $code = if ($_.Exception.Data.Contains('ExitCode')) { [int]$_.Exception.Data['ExitCode'] } else { 2 } if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { exit $code } $global:LASTEXITCODE = $code return }