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
2009-05-20 14:32: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
2009-05-20 14:35:17
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
2009-05-20 16:26:01
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
2009-05-21 11:22:32
+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
2009-05-20 14:39:48