如何使用 PowerShell 在大型二进制文件中查找和替换?

Tra*_*nin 1 binary powershell replace

我有大于 50 GB 的二进制文件,其中包含我想用等长全空格字符串替换的特定字符串。我正在寻找的字符串在文件的开头,比如在第一个兆字节内。如何使用 PowerShell 执行此操作?

恐怕[System.IO.File]::ReadAllBytes("myfile.bin")不是解决方案,因为我不想加载整个二进制文件。我想在第一兆字节内搜索和替换。

Mik*_*nko 6

从 C# 采用,因此可能需要进行一些重构:

$path = "\path\to\binary\file"

$numberOfBytesToRead = 1000000

$stringToSearch = "Hello World!"
$enc = [system.Text.Encoding]::UTF8
[Byte[]]$replacementString = $enc.GetBytes("     ");

$fileStream = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)

# binary reader to search for the string 
$binaryReader = New-Object System.IO.BinaryReader($fileStream)

# get the contents of the beginning of the file
[Byte[]] $byteArray = $binaryReader.ReadBytes($numberOfBytesToRead)

# look for string
$m = [Regex]::Match([Text.Encoding]::ASCII.GetString($byteArray), $stringToSearch)
if ($m.Success)
{    
    echo "Found '$stringToSearch' at position "$m.Index
}
else
{
    echo "'$stringToSearch' was not found"
}
$fileStream.Close()

# reopen to write
$fileStream = [System.IO.File]::Open($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Write, [System.IO.FileShare]::ReadWrite)

$binaryWriter = New-Object System.IO.BinaryWriter($fileStream)

# set file position to location of the string
$binaryWriter.BaseStream.Position = $m.Index; 
$binaryWriter.Write($replacementString)

$fileStream.Close()
Run Code Online (Sandbox Code Playgroud)