Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active August 13, 2023 23:28
Show Gist options
  • Save indented-automation/0538229c50c4370d172931183bc1adc8 to your computer and use it in GitHub Desktop.
Save indented-automation/0538229c50c4370d172931183bc1adc8 to your computer and use it in GitHub Desktop.
function Update-RegistryFile {
<#
.SYNOPSIS
Updates a registry file.
.DESCRIPTION
Line break and certain characters will not import from standard registry files (even if export works).
This function replaces any entry with line breaks with a hex value representing the string.
#>
[CmdletBinding()]
param (
# The path to the file to read and convert.
[Parameter(Mandatory, ValueFromPipeline)]
[ValidateScript( { Test-Path $_ -PathType Leaf } )]
[Alias('PSPath')]
[String]$Path,
# The output path. By default the new file is created derived from the original.
[String]$OutputPath
)
process {
$content = Get-Content -Path $Path -Raw
[Regex]::Matches($content, '(?<=^|\r?\n)"([^"]+)"="([^"]*\r?\n[^"]+)"') |
Sort-Object Index -Descending |
ForEach-Object {
$newValue = '"{0}"=hex(1):{1}' -f @(
$_.Groups.Item(1).Value
[System.Text.Encoding]::Unicode.GetBytes((
$_.Groups.Item(2).Value -replace '\r' -replace '\\\\', '\'
)).ForEach{ '{0:x2}' -f $_ } -join ','
)
$content = $content.Remove(
$_.Index,
$_.Value.Length
).Insert(
$_.Index,
$newValue
)
}
if (-not $OutputPath) {
$OutputPath = '{0}.Updated{1}' -f @(
[System.IO.Path]::GetFileNameWithoutExtension($Path)
[System.IO.Path]::GetExtension($Path)
)
}
Set-Content -Path $OutputPath -Value $content -NoNewline
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment