Convert Format-Hex PowerShell table to raw hex dump
Asked Answered
S

2

5

I used the Format-Hex command in PowerShell to get the hex contents of a string. My command "some_string" | format-hex gives me the output in a table. How can I make it into a raw hex dump so it's something like 736f6d655f737472696e67?

Stockdale answered 21/1, 2018 at 23:53 Comment(0)
E
10

Expand the Bytes property of the resulting object, format each byte as a double-digit hex number, then join them:

("some_string" | Format-Hex | Select-Object -Expand Bytes | ForEach-Object { '{0:x2}' -f $_ }) -join ''

However, it'd probably be simpler and more straightforward to write a custom function to converts a string to a hex representation:

function ConvertTo-Hex {
    [CmdletBinding()]
    Param(
        [Parameter(
            Position=0,
            Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true
        )]
        [string]$InputObject
    )

    $hex = [char[]]$InputObject |
           ForEach-Object { '{0:x2}' -f [int]$_ }

    if ($hex -ne $null) {
        return (-join $hex)
    }
}

"some_string" | ConvertTo-Hex
Exostosis answered 22/1, 2018 at 0:20 Comment(2)
This is exactly what I was looking for and works perfectly! I will take note of the simpler function you wrote about too. Thanks!Stockdale
@TamusJRoyce {0:x2} -> {0:X2} if you're referring to the code in my answer. Otherwise please ask a new question.Exostosis
A
2

Use Format-Hex:

(('Hello World' | Format-Hex).HexBytes).Replace(' ','')
48656C6C6F20576F726C64
Ancohuma answered 27/11, 2023 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.