Home > Mobile >  Check if the first n bytes of a file are specific in Powershell
Check if the first n bytes of a file are specific in Powershell

Time:02-01

How can I compare bytes from a file against a literal array of values?

$path = "C:\BinaryFile.bin"
$bytes = Get-Content -LiteralPath $path -Encoding byte -TotalCount 4 -ReadCount 4
if ($bytes -eq [0 1 2 3]) { # How to compare to expected bytes?
    Write-Output "OK: $bytes"
}

CodePudding user response:

Maybe compare-object. No output means equal. Syncwindow 0 for exact order.

$path = 'file'
[byte[]](0..3) | set-content $path -Encoding Byte
$bytes = Get-Content $path -Encoding byte -TotalCount 4
if (! (compare-object $bytes 0,1,2,3 -syncwindow 0)) { 
    "OK: $bytes"
}

Or do a string comparision:

if ("0 1 2 3" -eq $bytes) {
    "OK: $bytes"
}

CodePudding user response:

PowerShell doesn't have a built-in operator for sequence equality, but you can write your own little utility function fit for this purpose:

function Test-ArrayEquals
{
    param([array]$ReferenceArray, [array]$DifferenceArray)

    if($ReferenceArray.Length -ne $DifferenceArray.Length){
        # not same length, not equal
        return $false
    }

    for($i = 0; $i -lt $ReferenceArray.Length; $i  ){
        if($ReferenceArray[$i] -ne $DifferenceArray[$i]){
            # two aligned array members were found to not be equal
            return $false
        }
    }

    # we reached the end, array values must be equal
    return $true
}

Now you can do:

if (Test-ArrayEquals -ReferenceArray @(0, 1, 2, 3) -DifferenceArray $bytes) {
    # looks good!
}

CodePudding user response:

Arrays can be compared by Compare-Object. This reads the first four (4) bytes of a file and compares it to a literal array.

In Windows PowerShell 5.1:

Compare-Object `
    -ReferenceObject (Get-Content -Path '.\file.txt' -Encoding Byte -TotalCount 4)[0..3] `
    -DifferenceObject @(97,100,115,102)

In PowerShell Core 6.x :

Compare-Object `
    -ReferenceObject (Get-Content -Path '.\file.txt' -AsByteStream -TotalCount 4)[0..3] `
    -DifferenceObject @(97,100,115,102)
  •  Tags:  
  • Related