Skip to content

Instantly share code, notes, and snippets.

@logicplace
Created August 19, 2022 07:20
Show Gist options
  • Save logicplace/4dad9369724767d0386c10bd7b602ee9 to your computer and use it in GitHub Desktop.
Save logicplace/4dad9369724767d0386c10bd7b602ee9 to your computer and use it in GitHub Desktop.
function Write-RegistryOutput {
param (
[hashtable] $Keys
)
$Roots = @{
HKCR = "HKEY_CLASSES_ROOT"
HKCU = "HKEY_CURRENT_USER"
HKLM = "HKEY_LOCAL_MACHINE"
}
function escape {
param (
[string] $value
)
$value -replace '\\', '\\' -replace '"', '\"'
}
function FmtValue {
param (
[string] $value
)
if ($value.GetType().Name -eq 'String') {
# Write out just a default string
"`"$(escape $value)`""
} elseif ($value.GetType().Name -eq 'Int32') {
"dword:$value"
}
<#
The rest use hex representations
They're of the form hex(x):00,01,02
Where x can be:
* 2 - Expandable String
* 7 - Multi-String (three 00s for a newline, two 00s for the end)
* b - QWORD
Binary has no "(x)" part at all.
#>
}
$written = @{}
$out = "Windows Registry Editor Version 5.00"
$Keys.GetEnumerator() | Sort-Object Name | ForEach-Object {
$parts = $_.Key -split '\\'
$root, $rest = $parts
if ($Roots[$root]) { $root = $Roots[$root] }
$val = $_.Value
# Write out any empty headers needed, plus the needed header
$rest | ForEach-Object {
$root += "\$_"
if (! $written[$root]) {
$written[$root] = $true
$out += "`n`n[$root]"
}
}
$tmp = if ($val.GetType().Name -eq 'Hashtable') {
@(
'', '@', '(Default)' | ForEach-Object {
if ($val[$_]) {
$ret = "@=$(FmtValue $val[$_])"
Write-Host $val[$_]
$val.Remove($_)
$ret
}
}
) + (
$val.GetEnumerator() | Sort-Object Name | ForEach-Object {
"`"$(escape $_.Key)`"=$(FmtValue $_.Value)"
}
) -join "`n"
} else {
# Write out just a default value
"@=`"$(escape $val)`""
}
$out += "`n$tmp"
}
$out
}
function Import-RegistryFile {
param (
[string] $Path
)
if (Start-Process reg -ArgumentList "import $Path" -Verb runAs) {
Remove-Item -Path $Path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment