2

I am trying to get the contents of a file as hex in Powershell, and I am using the following:

get-content -encoding byte $fullFilePath | %{"{0:X2}" -f $_} | %{$hex = $hex + $_}

When I run this script, I do not get an error, but it does not return, it just hangs.

Any ideas?

Thanks.

2
  • 1
    How big is the file in $fullFilePath? You can skip the second ForEach-Object as well: Get-Content $fullFilePath -Encoding Byte | %{ $hex += "{0:X2}" -f $_ } -- tested with a few smaller files and $hex is populated very quickly. Testing with a 43MB PDF and it's been running for over two minutes. Commented Feb 7, 2014 at 16:28
  • Only 67k. I did wait longer, and it returned. Thanks for the help. PLEASE post as an answer so I can accept it. Commented Feb 7, 2014 at 16:33

2 Answers 2

3

That string concatenation is going to be a serious performance drag. I'd switch to using a stringbuilder:

$hex = New-Object System.Text.StringBuilder

get-content -encoding byte $fullFilePath | 
%{"{0:X2}" -f $_} | %{$hex.Append($_) > $null}

$hex = $hex.ToString()

Testing with a 125KB file dropped the run time from 58 seconds to 12 after switching from concatenation to using the stringbuilder.

Sign up to request clarification or add additional context in comments.

Comments

3

If you happen to be using the PowerShell Community Extensions, it has a Format-Hex command (alias fhex) e.g.:

get-content -encoding byte $fullFilePath | fhex

Comments

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.