1

This simple PowerShell script "fills in" the bad sectors of a USB flash drive. But I need to fill the drive with files containing 0x00 (all bits zero) and 0x255 (all bits 1). How can I use hex in PowerShell?

function filler {
    Param( [byte]$hex )

    $filearray = @()
    $count = 1
    $freespace = Get-PSDrive H
    $maxfiles = [int]($freespace.Free / 1048576)

    do {
        $randomnum = Get-Random -Minimum 100000000 -Maximum 999999999

        "$hex" * 1048576 | Out-File $randomnum

        $filecontent = Get-Content $randomnum -Raw

        if ($filecontent -notcontains ('$hex')) {
            # do nothing because the content is incorrect
        } else {
            $filearray += $randomnum
        }

        $count++
    } while ($count -le $maxfiles)

    foreach ($filename in $filearray) {
        Remove-Item $filename
    }
}

filler -hex 0x00
filler -hex 0xFF
1
  • [byte]$hex = 0xff; "$hex" * 5 doesn't do what you seem to expect. It creates the string "255255255255255" (repeat the string representation of the integer value 0xFF 5 times). Commented Mar 15, 2018 at 13:06

1 Answer 1

1

The string "0x00" is different from the numeric value represented by 0x00.

Make sure you specify -Encoding Byte when trying to read and write raw data to/from files:

,$hex * 1048576 | Set-Content $randomnum -Encoding Byte

And, similarly when reading from files:

$filecontent = Get-Content $randomnum -Encoding Byte
if($filecontent |Where-Object {$_ -notin @(0x00,0xFF)}){
    # do nothing
}
Sign up to request clarification or add additional context in comments.

2 Comments

Out-File: -Encoding Byte not exist. Used others but fills file more than 1MB. Get-Content: Should be -Encoding Byte.
@BillPaxtonn That's what I get for trying to write answers on my phone :-P Updated the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.