Files
BakNRet/tools/lab/Lab-Common.ps1
T
Shuery 232a82cd3c style: 逐条修静态分析告警(706 → 44),并把 MaxDepth 这条假承诺删掉
修掉的:空 catch 5 处;名词白名单 7 处;default-value 开关、自带 -WhatIf、lab 的明文口令与 irm|iex 各挂抑制并写明理由。

MaxDepth:它是分析器拓出来的真 bug —— 参数声明了却从未使用,也就是配置里的 CatalogMaxDepth 是假的,前缀补全实际只查 1 层,而配置注释与 README 都承诺「向下找几层」。按确认过的原则处理:**先让文档不撒谎**,所以把整条链路去掉(配置默认值、三个函数的参数、70 处实参、配置注释),而不是留一个假旋钮。零行为变化。想真的支持多层补全时,那是一个独立决定。

剩下 3 条都是分析器的误判,而且我实测确认过其中一条:$sourcePath 被报「赋值后从未使用」,我照着改成 $null = 之后,Set-StrictMode -Version 3.0 下读未定义变量直接抛错,Security 套件的 BeforeAll 挂掉、4 条用例连带失败。恢复后才绿。

这一类误判有共同成因:静态分析看不到「在传给 Test-Case / It / Where-Object 的 scriptblock 里被使用」。所以我只对能证明是误判的挂抑制并写明理由,不为了数字好看去改代码。

验收:test.ps1 9/9 全绿(7 与 5.1)、100 个文件两版解析零错、Run-RealSmoke 4/4。
2026-09-27 10:16:10 +08:00

188 lines
7.6 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<#
.SYNOPSIS
BakNRet 隔离测试环境的共享配置与工具函数(Hyper-V 真机级 VM)。
.DESCRIPTION
被 tools\lab\New-BakNRetLab.ps1(一次性搭建)与 tools\lab\Lab.ps1(日常使用)共同导入。
设计约定:
* 宿主机侧的一切状态(VHDX、日志、凭据、暂存包)都放在 $LabRoot 下,它刻意位于
**仓库之外**(默认 D:\VMs\BakNRet-Lab);测试用的归档、日志因此不会落进真实仓库,
真实仓库的 Backups\ 与 logs\ 在整套流程里只被读取、从不写入。
* VM 内的仓库副本在 C:\BakNRet,工具负载在 C:\BakNRet-Lab。
* 与 VM 的一切交互走 PowerShell Direct(VMBus),不依赖网络、不共享宿主机目录。
#>
$script:LabConfig = [ordered]@{
VmName = 'BakNRet-Lab'
LabRoot = 'D:\VMs\BakNRet-Lab'
VhdxPath = 'D:\VMs\BakNRet-Lab\vhdx\BakNRet-Lab.vhdx'
VhdxSizeGB = 80
IsoPath = 'F:\Images\Windows\Win11_25H2_Chinese_Simplified_x64_v2.iso'
ImageIndex = 4 # Windows 11 专业版
SwitchName = 'Default Switch'
MemoryStartupGB = 8
CpuCount = 8
GuestRepoPath = 'C:\BakNRet'
GuestLabPath = 'C:\BakNRet-Lab'
GuestUser = 'lab'
CheckpointName = 'clean-baseline'
RepoRoot = (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))
}
function Get-LabConfig { return $script:LabConfig }
function Get-LabPath {
<# .SYNOPSIS 取宿主机侧实验目录下的路径(自动建父目录)。 #>
param([Parameter(Mandatory)][string]$Relative)
$full = Join-Path $script:LabConfig.LabRoot $Relative
$parent = Split-Path -Parent $full
if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
return $full
}
function Write-LabLog {
<# .SYNOPSIS 统一日志:同时进控制台与 $LabRoot\logs\lab.log。 #>
param([Parameter(Mandatory)][string]$Message, [ValidateSet('INFO', 'WARN', 'ERROR', 'STEP')][string]$Level = 'INFO')
$line = "[{0}] [{1,-5}] {2}" -f (Get-Date).ToString('HH:mm:ss'), $Level, $Message
switch ($Level) {
'STEP' { Write-Host $line -ForegroundColor Cyan }
'WARN' { Write-Host $line -ForegroundColor Yellow }
'ERROR' { Write-Host $line -ForegroundColor Red }
default { Write-Host $line }
}
Add-Content -LiteralPath (Get-LabPath 'logs\lab.log') -Value $line -Encoding UTF8 -ErrorAction SilentlyContinue
}
function Test-LabElevated {
param()
return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Assert-LabElevated {
<# .SYNOPSIS 需要管理员:非同权限时给出可直接复制的提权命令。 #>
param([Parameter(Mandatory)][string]$Why)
if (Test-LabElevated) { return }
$gsudo = (Get-Command gsudo -ErrorAction SilentlyContinue | Select-Object -First 1).Source
$self = $MyInvocation.PSCommandPath
$hint = if ($gsudo) { "`n $gsudo pwsh -NoProfile -File `"$self`" $($MyInvocation.Line)" } else { '' }
throw "需要管理员权限:$Why$hint"
}
function Get-LabCredentialPath { return (Join-Path $script:LabConfig.LabRoot 'state\credentials.json') }
function Save-LabCredential {
<# .SYNOPSIS 把 VM 内 lab 账户的口令写进宿主机侧的 credentials.json(在仓库之外)。 #>
param([Parameter(Mandatory)][string]$Password)
$path = Get-LabCredentialPath
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $path) | Out-Null
[ordered]@{
VmName = $script:LabConfig.VmName
User = $script:LabConfig.GuestUser
Password = $Password
SavedAt = (Get-Date).ToString('s')
} | ConvertTo-Json | Set-Content -LiteralPath $path -Encoding UTF8
return $path
}
function Get-LabCredential {
<# .SYNOPSIS 读出 VM 凭据为 PSCredential。 #>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '',
Justification = '实验机的随机口令本来就得明文生成再注入 unattend.xml(Windows Setup 只接受那种形式)。它只活在本机实验环境,不进生产路径。')]
param()
$path = Get-LabCredentialPath
if (-not (Test-Path -LiteralPath $path)) { throw "找不到 VM 凭据:$path(先跑 New-BakNRetLab.ps1)" }
$j = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json
$sec = ConvertTo-SecureString $j.Password -AsPlainText -Force
return [pscredential]::new("$($j.User)", $sec)
}
function New-LabPassword {
<# .SYNOPSIS 生成只含字母数字的口令(避免 XML / 命令行转义问题)。 #>
param([int]$Length = 24)
$chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
return -join (1..$Length | ForEach-Object { $chars[(Get-Random -Minimum 0 -Maximum $chars.Length)] })
}
function Get-LabVm {
param()
return Get-VM -Name $script:LabConfig.VmName -ErrorAction SilentlyContinue
}
function Wait-LabVMRunning {
<# .SYNOPSIS 等 VM 进入 Running。 #>
param([int]$TimeoutSeconds = 300)
$sw = [Diagnostics.Stopwatch]::StartNew()
while ($sw.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
$vm = Get-LabVm
if ($vm -and $vm.State -eq 'Running') { return $true }
Start-Sleep -Seconds 3
}
return $false
}
function New-LabSession {
<# .SYNOPSIS 建立 PowerShell Direct 会话(VMBus,不经网络)。 #>
param([int]$RetrySeconds = 600)
$cred = Get-LabCredential
$sw = [Diagnostics.Stopwatch]::StartNew()
$lastError = $null
while ($sw.Elapsed.TotalSeconds -lt $RetrySeconds) {
try {
$s = New-PSSession -VMName $script:LabConfig.VmName -Credential $cred -ErrorAction Stop
Write-LabLog "PowerShell Direct 会话已建立(等待 $([math]::Round($sw.Elapsed.TotalSeconds)) 秒)"
return $s
}
catch {
$lastError = $_.Exception.Message
Start-Sleep -Seconds 5
}
}
throw "无法建立 PowerShell Direct 会话:$lastError"
}
function Invoke-LabCommand {
<# .SYNOPSIS 在 VM 里跑一段脚本并回传结果(自动建/收会话)。 #>
param(
[Parameter(Mandatory)][scriptblock]$ScriptBlock,
[object[]]$ArgumentList = @(),
[int]$RetrySeconds = 600
)
$s = New-LabSession -RetrySeconds $RetrySeconds
try {
return Invoke-Command -Session $s -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -ErrorAction Stop
}
finally {
Remove-PSSession -Session $s -ErrorAction SilentlyContinue
}
}
function Copy-LabFileToGuest {
<# .SYNOPSIS 宿主机 -> VM 传文件(Copy-VMFile,需要 Guest Service Interface)。 #>
param(
[Parameter(Mandatory)][string]$SourcePath,
[Parameter(Mandatory)][string]$DestinationPath
)
Copy-VMFile -VMName $script:LabConfig.VmName -SourcePath $SourcePath `
-DestinationPath $DestinationPath -CreateFullPath -FileSource Host -Force
}
function Get-HostSevenZip {
<# .SYNOPSIS 宿主机 7z 路径(用来打包仓库快照)。 #>
param()
$c = Get-Command 7z -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $c) { throw '宿主机找不到 7z' }
return $c.Source
}
function Test-LabGuestReady {
<# .SYNOPSIS 判断 VM 内供给是否完成(provision.ok)。 #>
param()
try {
$r = Invoke-LabCommand -ScriptBlock { Test-Path 'C:\BakNRet-Lab\state\provision.ok' } -RetrySeconds 60
return [bool]$r
}
catch { return $false }
}