Private/Write-KadenTextAtomic.ps1
|
function Write-KadenTextAtomic { <# .SYNOPSIS Replace a text file via a temp file and move. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Callers are private writers already gated by a public ShouldProcess command.')] [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$LiteralPath, [Parameter(Mandatory = $true)] [AllowEmptyString()] [string]$Text ) $utf8NoBom = New-Object System.Text.UTF8Encoding $false $directory = Split-Path -Parent $LiteralPath if (-not (Test-Path -LiteralPath $directory)) { New-Item -ItemType Directory -Path $directory -Force | Out-Null } $tempPath = Join-Path $directory ('.' + [guid]::NewGuid().ToString('N') + '.tmp') try { [System.IO.File]::WriteAllText($tempPath, $Text, $utf8NoBom) Move-Item -LiteralPath $tempPath -Destination $LiteralPath -Force } finally { if (Test-Path -LiteralPath $tempPath) { Remove-Item -LiteralPath $tempPath -Force -ErrorAction SilentlyContinue } } } |