PoshCode Archive  Artifact [a5b51e4952]

Artifact a5b51e495298a46b7172e66333efc674f7d08fe5e7a0999db7f19b0e680b171a:

  • File Get-Head.ps1 — part of check-in [90e5628915] at 2018-06-10 13:21:47 on branch trunk — Read the first few characters of a file … fast. (user: Joel Bennett size: 1220)

# encoding: ascii
# api: powershell
# title: Get-Head
# description: Read the first few characters of a file … fast.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Get-Head
# x-poshcode-id: 3184
# x-archived: 2017-03-31T03:12:56
# x-published: 2012-01-24T20:08:00
#
#
function Get-Head {
#.Synopsis
#  Read the first few characters of a file, fast.
param(
#  The path to the file (no powershell parsing happens here)
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Path","PSPath")]
[String]$FilePath, 
#  The number of characters you want to read
[Parameter(Mandatory=$false)]
[Int]$count=512, 
#  The encoding (UTF8 or ASCII)
[Parameter(Mandatory=$false)]
[ValidateSet("UTF8","ASCII")]
$encoding = "UTF8"
)
begin {
   if($encoding -eq "UTF8") {
      $decoder = New-Object System.Text.UTF8Encoding $true
   } else {
      $decoder = New-Object System.Text.AsciiEncoding
   }
   $buffer = New-Object Byte[] $count
}
process {
   $Stream = [System.IO.File]::Open($FilePath, 'Open', 'Read')
   $Null = $Stream.Read($buffer,0,$count)
   $decoder.GetString($buffer)
   $Stream.Close()
}
}