删除Powershell中的一些字节序列[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有一个* .bin文件。如何用powershell删除一些字节的部分字节(29个字节,标记为黄色),重复的字节序列(12个字节,标记为红色笔)?非常感谢!!

enter image description here

powershell binaryfiles
1个回答
1
投票

使用一个非常有用的文章和同上函数,我发现here,它似乎是可行的读取二进制文件并将其转换为字符串,而不是通过使用代码页28591更改任何字节。

有了这个(我略微更改了函数),你可以这样做来删除* .bin文件中的字节:

function ConvertTo-BinaryString {
    # converts the bytes of a file to a string that has a
    # 1-to-1 mapping back to the file's original bytes. 
    # Useful for performing binary regular expressions.
    [OutputType([String])]
    Param (
        [Parameter(Mandatory = $True, ValueFromPipeline = $True, Position = 0)]
        [ValidateScript( { Test-Path $_ -PathType Leaf } )]
        [String]$Path
    )

    $Stream = New-Object System.IO.FileStream -ArgumentList $Path, 'Open', 'Read'

    # Note: Codepage 28591 returns a 1-to-1 char to byte mapping
    $Encoding     = [Text.Encoding]::GetEncoding(28591)
    $StreamReader = New-Object System.IO.StreamReader -ArgumentList $Stream, $Encoding
    $BinaryText   = $StreamReader.ReadToEnd()

    $StreamReader.Close()
    $Stream.Close()

    return $BinaryText
}

$inputFile  = 'D:\test.bin'
$outputFile = 'D:\test2.bin'
$fileBytes  = [System.IO.File]::ReadAllBytes($inputFile)
$binString  = ConvertTo-BinaryString -Path $inputFile

# create your regex: 17 bytes in range of \x00 to \xFF followed by 12 bytes specific range
$re = [Regex]'[\x00-\xFF]{17}\xEB\x6F\xD3\x01\x18\x00{3}\xFF{3}\xFE'

# use a MemoryStream object to store the result
$ms  = New-Object System.IO.MemoryStream
$pos = $replacements = 0

$re.Matches($binString) | ForEach-Object {
    # write the part of the byte array before the match to the MemoryStream
    $ms.Write($fileBytes, $pos, $_.Index)
    # update the 'cursor' position for the next match
    $pos += ($_.Index + $_.Length)
    # and count the number of replacements done
    $replacements++
}

# write the remainder of the bytes to the stream
$ms.Write($fileBytes, $pos, $fileBytes.Count - $pos)

# save the updated bytes to a new file (will overwrite existing file)
[System.IO.File]::WriteAllBytes($outputFile, $ms.ToArray())
$ms.Dispose()

if ($replacements) {
    Write-Host "$replacements replacement(s) made."
}
else {
    Write-Host "Byte sequence not found. No replacements made."
}
© www.soinside.com 2019 - 2024. All rights reserved.