【问题标题】:Use hex byte in PowerShell?在 PowerShell 中使用十六进制字节?
【发布时间】:2018-03-15 21:34:27
【问题描述】:

这个简单的 PowerShell 脚本“填充”了 USB 闪存驱动器的坏扇区。但我需要用包含 0x00(所有位为零)和 0x255(所有位为 1)的文件填充驱动器。如何在 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

【问题讨论】:

  • [byte]$hex = 0xff; "$hex" * 5 并没有达到您的预期。它创建字符串“255255255255255”(将整数值 0xFF 的字符串表示重复 5 次)。

标签: windows powershell windows-10


【解决方案1】:

字符串"0x00"0x00表示的数值不同。

确保在尝试从文件读取和写入原始数据时指定-Encoding Byte

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

并且,从文件中读取时类似:

$filecontent = Get-Content $randomnum -Encoding Byte
if($filecontent |Where-Object {$_ -notin @(0x00,0xFF)}){
    # do nothing
}

【讨论】:

  • Out-File: -Encoding Byte 不存在。使用其他但填充文件超过 1MB。 Get-Content:应该是-Encoding Byte
  • @BillPaxtonn 这就是我尝试在手机上写答案的结果:-P 更新了答案
猜你喜欢
  • 2018-02-28
  • 2017-09-13
  • 2015-08-08
  • 2022-12-12
  • 2023-03-14
  • 2014-03-08
  • 2011-01-30
  • 1970-01-01
相关资源
最近更新 更多