Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created July 8, 2015 19:00
Show Gist options
  • Save Jaykul/9fa7de0aee3741cb90ce to your computer and use it in GitHub Desktop.
Save Jaykul/9fa7de0aee3741cb90ce to your computer and use it in GitHub Desktop.
Simple File IO with insufficient parameter handling
function Tail-File {
[CmdletBinding()]
param($Path,
[System.Text.Encoding]$Encoding = $([System.Text.Encoding]::UTF8)
)
$File = Convert-Path $Path
try {
$Stream = New-Object System.IO.FileStream $File, "Open", "Read", "ReadWrite", 2048, "None"
try {
$Reader = New-Object System.IO.StreamReader ([IO.Stream]$Stream), $Encoding
do {
$line = $reader.ReadLine()
if($line -ne $null) {
Write-Host $line
} else {
Start-Sleep -milli 250
}
} until ($line -match '^end_of_log')
} finally {
if($Reader) {
$Reader.Close()
$Reader.Dispose()
}
}
} finally {
if($Stream) {
$Stream.Dispose()
}
}
}
function Write-File {
param(
$Path,
$Content,
[System.Text.Encoding]$Encoding = $([System.Text.Encoding]::UTF8),
[Switch]$Line
)
$File = Convert-Path $Path
try {
$Stream = New-Object System.IO.FileStream $File, "OpenOrCreate", "ReadWrite", "ReadWrite", 2048, "None"
$Position = $Stream.Seek(0, "End")
try {
$Writer = New-Object System.IO.StreamWriter ([IO.Stream]$Stream), $Encoding
$Writer.Write($Content)
if($Line) {
$Writer.Write("`n")
}
} finally {
if($Writer) {
$Writer.Flush()
$Writer.Close()
$Writer.Dispose()
}
}
} finally {
if($Stream) {
$Stream.Dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment