Skip to content

Instantly share code, notes, and snippets.

@rufflabs
Created May 23, 2015 13:55
Show Gist options
  • Save rufflabs/699ec16bdd145c3fddcb to your computer and use it in GitHub Desktop.
Save rufflabs/699ec16bdd145c3fddcb to your computer and use it in GitHub Desktop.
Creates and cycles a log file
function Write-Log {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)][String]$Message,
[String]$Path = '',
[Int]$MaxFileSize = 1024000, # In bytes
[Switch]$NoNewLine,
[Switch]$Continued
)
# Create log file if needed
if(-Not (Test-Path $Path)) {
New-Item -Path $Path -ItemType File -Force
}
# Rotate log if file size is exceeded
if((Get-ChildItem $Path).Length -ge $MaxFileSize) {
Move-Item $Path "$($Path.TrimEnd('.txt'))-0.txt" -Force
New-Item -Path $Path -ItemType File -Force
}
if($Continued) {
$FullMessage = $Message
} else {
$FullMessage = "[$((Get-Date).ToString())] $($Message)"
}
if($NoNewLine) {
[IO.File]::AppendAllText($Path, $FullMessage)
} else {
Add-Content -Path $Path -Value $FullMessage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment