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.
Asked
Active
Viewed 9,972 times
8
-
1[This](http://stackoverflow.com/a/18936628/2707864) worked for me. And it does not traverse the whole file as `get-content`, so it is most convenient for large files. – sancho.s ReinstateMonicaCellio Apr 08 '16 at 18:28
2 Answers
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
-
14One 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
-
5Maybe 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
-
5It'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