PoshCode Logo PowerShell Code Repository

Get-Head by Joel Bennett 4 weeks ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/3184"></script>download | new post

Read the first few characters of a file … fast.

  1. function Get-Head {
  2. #.Synopsis
  3. #  Read the first few characters of a file, fast.
  4. param(
  5. #  The path to the file (no powershell parsing happens here)
  6. [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
  7. [Alias("Path","PSPath")]
  8. [String]$FilePath,
  9. #  The number of characters you want to read
  10. [Parameter(Mandatory=$false)]
  11. [Int]$count=512,
  12. #  The encoding (UTF8 or ASCII)
  13. [Parameter(Mandatory=$false)]
  14. [ValidateSet("UTF8","ASCII")]
  15. $encoding = "UTF8"
  16. )
  17. begin {
  18.    if($encoding -eq "UTF8") {
  19.       $decoder = New-Object System.Text.UTF8Encoding $true
  20.    } else {
  21.       $decoder = New-Object System.Text.AsciiEncoding
  22.    }
  23.    $buffer = New-Object Byte[] $count
  24. }
  25. process {
  26.    $Stream = [System.IO.File]::Open($FilePath, 'Open', 'Read')
  27.    $Null = $Stream.Read($buffer,0,$count)
  28.    $decoder.GetString($buffer)
  29.    $Stream.Close()
  30. }
  31. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me