Skip to content

Instantly share code, notes, and snippets.

@adrianmgg
Created March 28, 2023 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianmgg/021ee6b3d83b4cfa83741823803f8c92 to your computer and use it in GitHub Desktop.
Save adrianmgg/021ee6b3d83b4cfa83741823803f8c92 to your computer and use it in GitHub Desktop.
$ErrorActionPreference = 'Stop'
$timestamp_str = Get-Date -AsUTC -Format 'yyyy_MM_dd__HH_mm_ss'
$outdir = $PSScriptRoot
function backupregkeyhelper {
[CmdletBinding(SupportsShouldProcess)]
Param(
[Parameter(Mandatory)]
[string] $Path,
[Parameter(Mandatory)]
[string] $OutFileSlug
)
Process {
$tempfile = New-TemporaryFile -WhatIf:$false -Confirm:$false
$undated_outfile_hive = Join-Path $outdir "$OutFileSlug.hiv"
$dated_outfile_hive = Join-Path $outdir "$($OutFileSlug)__$timestamp_str.hiv"
$undated_outfile_text = Join-Path $outdir "$OutFileSlug.reg"
$dated_outfile_text = Join-Path $outdir "$($OutFileSlug)__$timestamp_str.reg"
try {
# TODO check if reg ran successfully
reg save $Path $tempfile /y | Out-Null
$new_hive = gc -AsByteStream -Raw -LiteralPath $tempfile
reg export $Path $tempfile /y | Out-Null
$new_text = gc -AsByteStream -Raw -LiteralPath $tempfile
# get most recent data if any already saved
$old_text = gc -AsByteStream -Raw -ErrorAction SilentlyContinue -LiteralPath $undated_outfile_text
# we need to save the current data if a) there's no old data saved, or b) the data has changed
$needs_save = ($old_text -eq $null) -or (@(Compare-Object -SyncWindow 0 $old_text $new_text).Length -gt 0)
if($needs_save) {
# TODO: doesn't properly handle -Confirm yes/no to all options
# https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-shouldprocess
Set-Content -LiteralPath $undated_outfile_hive -Value $new_hive -AsByteStream
Set-Content -LiteralPath $dated_outfile_hive -Value $new_hive -AsByteStream
Set-Content -LiteralPath $undated_outfile_text -Value $new_text -AsByteStream
Set-Content -LiteralPath $dated_outfile_text -Value $new_text -AsByteStream
}
} finally {
ri -WhatIf:$false -Confirm:$false -ErrorAction SilentlyContinue $tempfile
}
}
}
$regpath_machine_env = 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
$regpath_user_env = 'HKCU\Environment'
backupregkeyhelper -Path $regpath_machine_env -OutFileSlug 'system_env'
backupregkeyhelper -Path $regpath_user_env -OutFileSlug 'user_env'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment