tags:

views:

104

answers:

2

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.

A: 

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
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
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
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
+6  A: 
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
that is a useful magic incantation!
Cheeso