Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Last active May 5, 2026 13:26
Show Gist options
  • Select an option

  • Save bixb0012/a11ec0533eb21d479f79eb2884ac4c64 to your computer and use it in GitHub Desktop.

Select an option

Save bixb0012/a11ec0533eb21d479f79eb2884ac4c64 to your computer and use it in GitHub Desktop.
PowerShell: In-place File Modify
#Requires -Version 5.1
# Reference: 1) https://learn.microsoft.com/en-us/dotnet/api/system.io.file.replace?view=netframework-4.8.1
# Reference: 2) https://learn.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8.1
# Reference: 3) https://learn.microsoft.com/en-us/dotnet/api/system.io.filemode?view=netframework-4.8.1
# Reference: 4) https://learn.microsoft.com/en-us/dotnet/api/system.io.fileaccess?view=netframework-4.8.1
# Example 1: Atomic in-place file replace using File.Replace, which swaps a source file into
# the destination path atomically, preserving the destination's ACLs, ownership, and metadata
# while optionally retaining a backup of the original destination file
$SourcePath = "" # Path to source/replacement file
$DestinationPath = "" # Path to destination file to be replaced
$BackupPath = "" # Path for backup of destination, or $null to skip
[System.IO.File]::Replace($SourcePath, $DestinationPath, $BackupPath)
if (Test-Path -LiteralPath $BackupPath) { Remove-Item -LiteralPath $BackupPath -Force }
# Example 2: In-place file overwrite via truncate and stream copy, preserving the destination
# file's ACLs and ownership by writing through the existing file handle rather than replacing
# the file object itself.
$SourcePath = "" # Path to source file
$DestinationPath = "" # Path to destination file to overwrite in place
$InputStream = $null
$OutputStream = $null
try {
$InputStream = [System.IO.File]::OpenRead($SourcePath)
$OutputStream = [System.IO.File]::Open(
$DestinationPath,
[System.IO.FileMode]::Truncate,
[System.IO.FileAccess]::Write)
$InputStream.CopyTo($OutputStream)
} catch {
Write-Error "In-place overwrite failed for '$DestinationPath'. Error: $_"
} finally {
if ($null -ne $InputStream) { $InputStream.Dispose() }
if ($null -ne $OutputStream) { $OutputStream.Dispose() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment