Question:
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
?
Answer:
Expand the Bytes
property of the resulting object, format each byte as a double-digit hex number, then join them:
1 2 |
("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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 |