8

Its pretty straightforward to get the first x lines of a text file, but I need the first x MB of a file. Given that I'm a PowerShell neophyte if you could please give me some annotations on the script that would be greatly appreciated.

Ralph Shillington
  • 20,718
  • 23
  • 91
  • 154

2 Answers2

15
Get-Content foo.exe -TotalCount 1MB -Encoding byte

If you happen to be using PowerShell Community Extensions then do this:

Format-Hex foo.exe -count 1MB

Note: If you are using PowerShell V2 be sure to grab the 1.2 beta of PSCX.

Keith Hill
  • 964
  • 5
  • 5
3

Independent of PowerShell, I'd just use the head command. (It's a standard Unix command, but it's available for Windows.) The -c option lets you specify the number of bytes you want.

head -c 1024 foo.exe
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • 14
    One of the reasons I loath asking powershell questions is the for the obvious "you could do it unix with ...." answers. there's got to be a dozen of non-powershell ways of getting what I'm looking for, but I"m looking for a powershell answer. – Ralph Shillington May 20 '09 at 14:35
  • And I don't understand why anyone would restrict solutions to PowerShell when there are solutions that work everywhere, not just PowerShell. I mean, unless it's just idle curiosity: "Gee, I wonder if I can do that in PowerShell." You didn't say it needed to be a PowerShell-only solution. I figured you're just sitting at a PS prompt and wondering how to get the first N bytes of a file. The answer is the same as if you were sitting at any other prompt, and it's not a Unix solution, either. – Rob Kennedy May 20 '09 at 16:26
  • 5
    Maybe someday you don't want to read the first 1 KiB of a file but from a binary registry key. Also, there are ofttimes things you miss in a new technology because you're too accustomed doing it your old-fashioned way. You wouldn't recommend using sed/awk on wmic output to a Powershell user, would you? Also, head (being not a cmdlet) will yield a string[] which may not be what you want. – Joey May 21 '09 at 11:22
  • 5
    It's important to realize that there are often cases where a machine is locked down so that you can't install new software, but you *can* run PowerShell. That's a good use-case for "want PowerShell, can't use X ported unix executable" – djsadinoff Dec 26 '10 at 12:49