Am trying to perform binary hex edit from the command line using only powershell. Have had partial success performing a hex replace with this snip. Problem springs up when
As far as I can oversee the quest, there is no need to do any hexadecimal conversion on a byte stream to do a replacement. You can just do a replacement on a decimal value list (default string conversion) where the values are bounded by spaces (word ends), e.g.:
(I am skipping the file input/output which is already explained in the answer from @mklement0)
$bInput = [Byte[]](0x69, 0x52, 0x6f, 0x6e, 0x57, 0x61, 0x73, 0x48, 0x65, 0x72, 0x65)
$bOriginal = [Byte[]](0x57, 0x61, 0x73, 0x48)
$bSubstitute = [Byte[]](0x20, 0x77, 0x61, 0x73, 0x20, 0x68)
$bOutput = [Byte[]]("$bInput" -Replace "\b$bOriginal\b", "$bSubstitute" -Split '\s+')
In case you like to use hexadecimal strings (e.g. for the replace arguments), you can convert a hex string to a byte array as follows: [Byte[]]('123456' -Split '(..)' | ? { $_ } | % {[Convert]::toint16($_, 16)})
Note that this solution supports different $bOriginal
and $bSubstitute
lengths. In such a case, if you like to start replacing from a specific offset you might want to use the Select-Object cmdlet:
$Offset = 3
$bArray = $bInput | Select -Skip $Offset
$bArray = [Byte[]]("$bArray" -Replace "\b$bOriginal\b", "$bSubstitute" -Split '\s+')
$bOutput = ($bInput | Select -First $Offset) + $bArray