Standardize script status colors and friendly error boundaries
This commit is contained in:
parent
4a221734d6
commit
a801f8ca0b
1
TASKS.md
1
TASKS.md
|
|
@ -136,3 +136,4 @@ open until it is run on disposable machines with the required account setups.
|
|||
- [x] Preserve existing registry keys during MPC-HC apply and document registry-only storage and capture filtering.
|
||||
- [x] Restore SSH firewall state using enum names, preserve retry state on cleanup failure, and show the elevated error without a wrapper stack trace.
|
||||
- [x] Install MPC-HC through clsid2.mpc-hc and link its config to the package result.
|
||||
- [x] Standardize entrypoint error summaries, status colors, plain redirected output, and automation exit codes across setup, updates, capture, CLI, and SSH.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,30 @@ param(
|
|||
[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
|
||||
|
|
@ -169,7 +193,7 @@ if (($userPath -split ';') -notcontains $launcherDirectory) {
|
|||
$env:Path = "$env:Path;$launcherDirectory"
|
||||
}
|
||||
|
||||
Write-Host "Config Central configured for '$Machine'."
|
||||
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,
|
||||
|
|
@ -178,3 +202,14 @@ if (-not $SkipApply) {
|
|||
& $powerShell7 @applyArguments
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
$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
|
||||
}
|
||||
|
|
|
|||
27
cc.ps1
27
cc.ps1
|
|
@ -13,15 +13,38 @@ param(
|
|||
[string]$Revision
|
||||
)
|
||||
|
||||
# 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 }
|
||||
}
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
try {
|
||||
foreach ($module in @('State', 'Manifest', 'Repository', 'Packages', 'Adapters', 'Configs', 'Elevation', 'Scheduling', 'Core')) {
|
||||
$path = Join-Path $PSScriptRoot "src/$module.psm1"
|
||||
if (Test-Path -LiteralPath $path) { Import-Module $path -Force }
|
||||
}
|
||||
|
||||
try {
|
||||
$paths = Get-ConfigCentralPaths -DataRoot $DataRoot
|
||||
Initialize-ConfigCentralData $paths
|
||||
$settings = Read-JsonState -Path $paths.Settings -Default ([ordered]@{})
|
||||
|
|
@ -41,6 +64,6 @@ try {
|
|||
}
|
||||
catch {
|
||||
$errorResult = [ordered]@{ command = $Command; succeeded = $false; exitCode = 2; error = $_.Exception.Message }
|
||||
if ($Json) { $errorResult | ConvertTo-Json -Depth 8 } else { [Console]::Error.WriteLine("Config Central could not complete: " + $errorResult.error) }
|
||||
if ($Json) { $errorResult | ConvertTo-Json -Depth 8 } else { Write-ConfigCentralMessage -Level Error -Message ("Config Central could not complete: " + $errorResult.error) }
|
||||
exit 2
|
||||
}
|
||||
|
|
|
|||
49
install.ps1
49
install.ps1
|
|
@ -7,6 +7,30 @@ param(
|
|||
[switch]$PreserveLocalConfigs
|
||||
)
|
||||
|
||||
# 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
|
||||
|
|
@ -37,20 +61,20 @@ function Write-SetupFailure {
|
|||
Write-Host ''
|
||||
switch ($ExitCode) {
|
||||
5 {
|
||||
Write-Host 'Setup finished with some items needing attention.' -ForegroundColor Yellow
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'Setup finished with some items needing attention.'
|
||||
Write-Host 'Successful changes were kept. Review the Failed, Conflict, or Skipped items above.'
|
||||
Write-Host 'Fix the reported issue, then rerun setup; completed items will be checked and skipped when current.'
|
||||
}
|
||||
6 {
|
||||
Write-Host 'Setup completed. Windows needs a restart to finish installation.' -ForegroundColor Yellow
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'Setup completed. Windows needs a restart to finish installation.'
|
||||
Write-Host 'Restart when convenient; Config Central will not restart this computer automatically.'
|
||||
}
|
||||
10 {
|
||||
Write-Host 'Another Config Central update is already running.' -ForegroundColor Yellow
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'Another Config Central update is already running.'
|
||||
Write-Host 'Wait for it to finish, then rerun setup.'
|
||||
}
|
||||
default {
|
||||
Write-Host "Setup could not complete (exit code $ExitCode)." -ForegroundColor Yellow
|
||||
Write-ConfigCentralMessage -Level Error -Message "Setup could not complete (exit code $ExitCode)."
|
||||
Write-Host 'Review the diagnostic above, correct the problem, and rerun setup.'
|
||||
}
|
||||
}
|
||||
|
|
@ -67,7 +91,7 @@ function Get-SavedMachine {
|
|||
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
|
||||
if ($settings.machine -match '^[a-z0-9][a-z0-9-]*$') { return [string]$settings.machine }
|
||||
}
|
||||
catch { Write-Warning "Ignoring unreadable existing settings: $($_.Exception.Message)" }
|
||||
catch { Write-ConfigCentralMessage -Level Warning -Message "Ignoring unreadable existing settings: $($_.Exception.Message)" }
|
||||
return $null
|
||||
}
|
||||
|
||||
|
|
@ -83,7 +107,7 @@ function Get-AvailableMachines {
|
|||
)
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Could not list machine manifests: $($_.Exception.Message)"
|
||||
Write-ConfigCentralMessage -Level Warning -Message "Could not list machine manifests: $($_.Exception.Message)"
|
||||
return @()
|
||||
}
|
||||
}
|
||||
|
|
@ -168,9 +192,20 @@ try {
|
|||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host "Config Central is ready for '$Machine'."
|
||||
Write-ConfigCentralMessage -Level Success -Message "Config Central is ready for '$Machine'."
|
||||
Write-Host 'Run the web update-configs.ps1 command for config updates, or rerun this installer to repair setup.'
|
||||
}
|
||||
finally {
|
||||
Remove-Item -LiteralPath $bootstrapPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
$global:LASTEXITCODE = 0
|
||||
}
|
||||
catch {
|
||||
Write-ConfigCentralMessage -Level Error -Message "Setup 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,7 +156,7 @@ function Export-ConfigCapture {
|
|||
elseif ($config.mode -eq 'registry' -and $config.name -eq 'mpc-hc-settings') {
|
||||
$destination = Join-Path $captureRoot 'review\mpc-hc-settings\settings.json'
|
||||
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
|
||||
& (Join-Path $RepositoryRoot 'tools\Export-MpcHcSettings.ps1') -OutputPath $destination
|
||||
& (Join-Path $RepositoryRoot 'tools\Export-MpcHcSettings.ps1') -OutputPath $destination -ThrowOnError 6>$null
|
||||
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Review'; message = $destination })
|
||||
continue
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,7 +211,10 @@ function Write-ConfigCentralResult {
|
|||
Write-Host ("{0,-10} {1,-24} {2}" -f $state, $operation.name, $message)
|
||||
}
|
||||
}
|
||||
foreach ($warning in @($Result.warnings)) { Write-Warning $warning }
|
||||
foreach ($warning in @($Result.warnings)) {
|
||||
if ($useColor) { Write-Host "Warning: $warning" -ForegroundColor Yellow }
|
||||
else { Write-Host "Warning: $warning" }
|
||||
}
|
||||
}
|
||||
|
||||
function Show-ConfigCentralMenu {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
BeforeAll {
|
||||
$messageTokens = $null; $messageErrors = $null
|
||||
$messageAst = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../bootstrap.ps1", [ref]$messageTokens, [ref]$messageErrors)
|
||||
$messageFn = $messageAst.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Write-ConfigCentralMessage' }, $true)
|
||||
. ([scriptblock]::Create($messageFn.Extent.Text))
|
||||
|
||||
$script:bootstrapPath = "$PSScriptRoot/../bootstrap.ps1"
|
||||
$tokens = $null
|
||||
$errors = $null
|
||||
|
|
@ -19,8 +24,8 @@ Describe 'Bootstrap invocation' {
|
|||
$previousLocalAppData = $env:LOCALAPPDATA
|
||||
try {
|
||||
$env:LOCALAPPDATA = $TestDrive
|
||||
{ & $bootstrap -Repository 'https://example.invalid/config-central.git' -Machine test } |
|
||||
Should -Throw '*must be downloaded and run as a file*'
|
||||
& $bootstrap -Repository 'https://example.invalid/config-central.git' -Machine test
|
||||
$LASTEXITCODE | Should -Be 2
|
||||
}
|
||||
finally { $env:LOCALAPPDATA = $previousLocalAppData }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
BeforeAll {
|
||||
$messageTokens = $null; $messageErrors = $null
|
||||
$messageAst = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../install.ps1", [ref]$messageTokens, [ref]$messageErrors)
|
||||
$messageFn = $messageAst.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Write-ConfigCentralMessage' }, $true)
|
||||
. ([scriptblock]::Create($messageFn.Extent.Text))
|
||||
|
||||
$script:installerPath = "$PSScriptRoot/../install.ps1"
|
||||
$tokens = $null
|
||||
$errors = $null
|
||||
|
|
@ -109,7 +114,8 @@ Describe 'Friendly setup outcomes' {
|
|||
Should -Invoke Write-Host -ParameterFilter { $Object -like '*Wait for it to finish*' } -Times 1
|
||||
}
|
||||
It 'retains unknown error codes in the summary' {
|
||||
Mock Write-ConfigCentralMessage {}
|
||||
Write-SetupFailure -ExitCode 123
|
||||
Should -Invoke Write-Host -ParameterFilter { $Object -like '*exit code 123*' } -Times 1
|
||||
Should -Invoke Write-ConfigCentralMessage -ParameterFilter { $Level -eq 'Error' -and $Message -like '*exit code 123*' } -Times 1
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
BeforeAll {
|
||||
$script:entrypoints = @('install.ps1', 'bootstrap.ps1', 'update-configs.ps1', 'cc.ps1', 'tools/TemporarySsh.ps1', 'tools/Export-MpcHcSettings.ps1')
|
||||
$script:formatters = foreach ($entry in $entrypoints) {
|
||||
$tokens = $null; $errors = $null
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../$entry", [ref]$tokens, [ref]$errors)
|
||||
$fn = $ast.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Write-ConfigCentralMessage' }, $true)
|
||||
if (-not $fn) { throw "Missing message formatter in $entry" }
|
||||
$fn.Extent.Text
|
||||
}
|
||||
. ([scriptblock]::Create($formatters[0]))
|
||||
}
|
||||
|
||||
Describe 'Consistent standalone output' {
|
||||
It 'uses the same dependency-free formatter in every entrypoint' {
|
||||
foreach ($formatter in $formatters) { $formatter | Should -BeExactly $formatters[0] }
|
||||
}
|
||||
It 'honors NO_COLOR for human status output' {
|
||||
$previous = $env:NO_COLOR
|
||||
try {
|
||||
$env:NO_COLOR = '1'
|
||||
Mock Write-Host {}
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'Try again'
|
||||
Should -Invoke Write-Host -Times 1 -ParameterFilter { $Object -eq 'Try again' -and -not $PSBoundParameters.ContainsKey('ForegroundColor') }
|
||||
}
|
||||
finally { $env:NO_COLOR = $previous }
|
||||
}
|
||||
It 'writes errors to stderr without creating a second exception' {
|
||||
$previous = [Console]::Error
|
||||
$previousColor = $env:NO_COLOR
|
||||
$capture = [IO.StringWriter]::new()
|
||||
try {
|
||||
$env:NO_COLOR = '1'
|
||||
[Console]::SetError($capture)
|
||||
{ Write-ConfigCentralMessage -Level Error -Message 'Could not read settings' } | Should -Not -Throw
|
||||
$capture.ToString().Trim() | Should -BeExactly 'Could not read settings'
|
||||
}
|
||||
finally { [Console]::SetError($previous); $env:NO_COLOR = $previousColor; $capture.Dispose() }
|
||||
}
|
||||
It 'reports unsupported-platform or missing-registry errors cleanly as file entrypoints' -Skip:$IsWindows {
|
||||
foreach ($entry in @('install.ps1', 'update-configs.ps1', 'tools/TemporarySsh.ps1', 'tools/Export-MpcHcSettings.ps1')) {
|
||||
$output = & (Join-Path $PSHOME 'pwsh') -NoProfile -File "$PSScriptRoot/../$entry" 2>&1
|
||||
$LASTEXITCODE | Should -BeGreaterThan 0
|
||||
($output | Out-String) | Should -Match 'could not complete'
|
||||
($output | Out-String) | Should -Not -Match 'CategoryInfo|FullyQualifiedErrorId|Write-Error:'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,9 @@
|
|||
BeforeAll {
|
||||
$messageTokens = $null; $messageErrors = $null
|
||||
$messageAst = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../tools/TemporarySsh.ps1", [ref]$messageTokens, [ref]$messageErrors)
|
||||
$messageFn = $messageAst.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Write-ConfigCentralMessage' }, $true)
|
||||
. ([scriptblock]::Create($messageFn.Extent.Text))
|
||||
|
||||
$script:temporarySshPath = "$PSScriptRoot/../tools/TemporarySsh.ps1"
|
||||
$tokens = $null; $errors = $null
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseFile($temporarySshPath, [ref]$tokens, [ref]$errors)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
BeforeAll {
|
||||
$messageTokens = $null; $messageErrors = $null
|
||||
$messageAst = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../update-configs.ps1", [ref]$messageTokens, [ref]$messageErrors)
|
||||
$messageFn = $messageAst.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Write-ConfigCentralMessage' }, $true)
|
||||
. ([scriptblock]::Create($messageFn.Extent.Text))
|
||||
|
||||
$tokens = $null; $errors = $null
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../update-configs.ps1", [ref]$tokens, [ref]$errors)
|
||||
if ($errors.Count) { throw $errors[0] }
|
||||
|
|
|
|||
|
|
@ -1,9 +1,34 @@
|
|||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputPath = (Join-Path $PSScriptRoot '..\configs\mpc-hc\settings.json'),
|
||||
[switch]$IncludePrivateValues
|
||||
[switch]$IncludePrivateValues,
|
||||
[switch]$ThrowOnError
|
||||
)
|
||||
|
||||
# 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 Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
|
|
@ -42,5 +67,17 @@ $document = [ordered]@{ schemaVersion = 1; values = @($values | Sort-Object path
|
|||
$fullOutputPath = [IO.Path]::GetFullPath($OutputPath)
|
||||
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $fullOutputPath) -Force)
|
||||
$document | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $fullOutputPath -Encoding utf8NoBOM
|
||||
Write-Host "Exported $($values.Count) MPC-HC values to '$fullOutputPath'."
|
||||
Write-Warning 'Review the file for machine-specific paths or private history before committing it.'
|
||||
Write-ConfigCentralMessage -Level Success -Message "Exported $($values.Count) MPC-HC values to '$fullOutputPath'."
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'Review the file for machine-specific paths or private history before committing it.'
|
||||
|
||||
$global:LASTEXITCODE = 0
|
||||
}
|
||||
catch {
|
||||
if ($ThrowOnError) { throw }
|
||||
Write-ConfigCentralMessage -Level Error -Message "MPC-HC capture 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,29 @@ param(
|
|||
[string]$ResultPath
|
||||
)
|
||||
|
||||
# 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 }
|
||||
}
|
||||
|
||||
Set-StrictMode -Version 2.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
|
|
@ -38,7 +61,7 @@ function Invoke-ElevatedCopy {
|
|||
}
|
||||
throw "The administrator helper exited with code $($process.ExitCode) without reporting details."
|
||||
}
|
||||
Write-Host "Temporary SSH $($Action.ToLowerInvariant()) completed."
|
||||
Write-ConfigCentralMessage -Level Success -Message "Temporary SSH $($Action.ToLowerInvariant()) completed."
|
||||
|
||||
}
|
||||
finally { Remove-Item -LiteralPath $temporaryScript, $resultFile -Force -ErrorAction SilentlyContinue }
|
||||
|
|
@ -60,7 +83,7 @@ function Install-OpenSshServer {
|
|||
--accept-source-agreements `
|
||||
--override 'REMOVE=Client'
|
||||
if ($LASTEXITCODE -eq 0 -and (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { return }
|
||||
Write-Warning "The fast OpenSSH install did not produce the sshd service (WinGet exit $LASTEXITCODE); falling back to the Windows capability."
|
||||
Write-ConfigCentralMessage -Level Warning -Message "The fast OpenSSH install did not produce the sshd service (WinGet exit $LASTEXITCODE); falling back to the Windows capability."
|
||||
}
|
||||
|
||||
$capability = Get-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0'
|
||||
|
|
@ -84,7 +107,7 @@ function Disable-TemporarySsh {
|
|||
$temporaryRule = Get-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue
|
||||
if ($temporaryRule) { Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction Stop }
|
||||
if ($null -eq $state) {
|
||||
Write-Warning 'No temporary SSH state was found. The dedicated firewall rule was removed.'
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'No temporary SSH state was found. The dedicated firewall rule was removed.'
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -102,7 +125,7 @@ function Disable-TemporarySsh {
|
|||
Start-Process -FilePath 'powershell.exe' -WindowStyle Hidden -ArgumentList @('-NoProfile', '-Command', $stopCommand) | Out-Null
|
||||
}
|
||||
Remove-Item -LiteralPath $statePath -Force
|
||||
Write-Host 'Temporary SSH firewall cleanup completed.'
|
||||
Write-ConfigCentralMessage -Level Success -Message 'Temporary SSH firewall cleanup completed.'
|
||||
if (-not $state.serviceWasRunning) { Write-Host 'The SSH service will stop shortly; an active SSH session may disconnect.' }
|
||||
else { Write-Host 'SSH was already running before temporary access and has been left running.' }
|
||||
return
|
||||
|
|
@ -169,12 +192,12 @@ try {
|
|||
$sshdConfig = Join-Path $env:ProgramData 'ssh\sshd_config'
|
||||
if (Test-Path -LiteralPath $sshdConfig -PathType Leaf) {
|
||||
$passwordDisabled = Select-String -LiteralPath $sshdConfig -Pattern '^\s*PasswordAuthentication\s+no\s*$' -Quiet
|
||||
if ($passwordDisabled) { Write-Warning 'Password authentication is disabled in sshd_config; use an existing SSH key.' }
|
||||
if ($passwordDisabled) { Write-ConfigCentralMessage -Level Warning -Message 'Password authentication is disabled in sshd_config; use an existing SSH key.' }
|
||||
}
|
||||
|
||||
$privateProfiles = @(Get-NetConnectionProfile -ErrorAction SilentlyContinue | Where-Object NetworkCategory -eq 'Private')
|
||||
if ($privateProfiles.Count -eq 0) {
|
||||
Write-Warning 'No active Private network profile was found. The temporary firewall rule will remain closed on Public networks.'
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'No active Private network profile was found. The temporary firewall rule will remain closed on Public networks.'
|
||||
}
|
||||
|
||||
$addresses = @(
|
||||
|
|
@ -186,10 +209,10 @@ try {
|
|||
)
|
||||
|
||||
Write-Host ''
|
||||
Write-Host 'Temporary SSH access is ready. From CachyOS, open PowerShell directly with one of:'
|
||||
Write-ConfigCentralMessage -Level Success -Message 'Temporary SSH access is ready. From CachyOS, open PowerShell directly with one of:'
|
||||
foreach ($address in $addresses) { Write-Host " ssh -t $env:USERNAME@$address powershell.exe -NoLogo -NoProfile" }
|
||||
if ($addresses.Count -eq 0) {
|
||||
Write-Warning 'No usable IPv4 address was found. Run ipconfig and use the address of the Private network adapter.'
|
||||
Write-ConfigCentralMessage -Level Warning -Message 'No usable IPv4 address was found. Run ipconfig and use the address of the Private network adapter.'
|
||||
}
|
||||
Write-Host ''
|
||||
Write-Host 'Use the Windows account password, not a Windows Hello PIN.'
|
||||
|
|
@ -205,7 +228,7 @@ catch {
|
|||
@{ message = $message } | ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8
|
||||
}
|
||||
Write-Host ''
|
||||
Write-Host "Temporary SSH $($Action.ToLowerInvariant()) could not complete." -ForegroundColor Yellow
|
||||
Write-ConfigCentralMessage -Level Error -Message "Temporary SSH $($Action.ToLowerInvariant()) could not complete."
|
||||
Write-Host $message
|
||||
if ($Action -eq 'Disable') {
|
||||
Write-Host 'Access may still be enabled. Retry Disable from a local administrator PowerShell window.'
|
||||
|
|
|
|||
|
|
@ -4,6 +4,29 @@ param(
|
|||
[switch]$ForceConfigs = $true
|
||||
)
|
||||
|
||||
# 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 }
|
||||
}
|
||||
|
||||
function Invoke-ConfigUpdate {
|
||||
param([string]$DataRoot, [switch]$ForceConfigs = $true)
|
||||
$settingsPath = Join-Path $DataRoot 'settings.json'
|
||||
|
|
@ -44,9 +67,11 @@ function Invoke-ConfigUpdate {
|
|||
if ($ForceConfigs) { $arguments += '-ForceConfigs' }
|
||||
& $pwshPath @arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Config update did not fully complete (exit $LASTEXITCODE). Review the results above; backups and logs remain in '$DataRoot'."
|
||||
$failure = [Exception]::new("Config update did not fully complete (exit $LASTEXITCODE). Review the item results above; backups and logs remain in '$DataRoot'.")
|
||||
$failure.Data['ExitCode'] = [int]$LASTEXITCODE
|
||||
throw $failure
|
||||
}
|
||||
Write-Host 'Configs are up to date.'
|
||||
Write-ConfigCentralMessage -Level Success -Message 'Configs are up to date.'
|
||||
}
|
||||
finally {
|
||||
$env:GIT_TERMINAL_PROMPT = $previousGitPrompt
|
||||
|
|
@ -54,6 +79,7 @@ function Invoke-ConfigUpdate {
|
|||
}
|
||||
}
|
||||
|
||||
try {
|
||||
# Keep strict mode and error preferences local to this invocation.
|
||||
& {
|
||||
Set-StrictMode -Version 2.0
|
||||
|
|
@ -61,3 +87,14 @@ function Invoke-ConfigUpdate {
|
|||
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Config updates run only on Windows.' }
|
||||
Invoke-ConfigUpdate -DataRoot (Join-Path $env:LOCALAPPDATA 'ConfigCentral') -ForceConfigs:$ForceConfigs
|
||||
}
|
||||
|
||||
$global:LASTEXITCODE = 0
|
||||
}
|
||||
catch {
|
||||
Write-ConfigCentralMessage -Level Error -Message "Config update 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
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue