function Write-BaknretAtomicText { <# .SYNOPSIS 原子写一个文本文件(先写 .tmp,再替换)。 #> param( [Parameter(Mandatory = $true)][string]$Path, [AllowEmptyString()][string]$Text = '' ) $directory = Split-Path -Parent $Path if ($directory -and -not (Test-Path -LiteralPath $directory)) { New-Item -ItemType Directory -Path $directory -Force | Out-Null } $temp = "$Path.tmp" [System.IO.File]::WriteAllText($temp, $Text, $script:LogEncoding) if (-not (Test-Path -LiteralPath $Path)) { Move-BaknretArchiveIntoPlace -TempPath $temp -DestinationPath $Path return $Path } # 目标已存在:用 File.Replace。失败时旧内容完好、.tmp 留着便于排查(两版实测一致)—— # 这正是"宁可这次没换成,也不能让目标消失"。 [System.IO.File]::Replace($temp, $Path, [NullString]::Value) return $Path }