Skip to content

Instantly share code, notes, and snippets.

@martin9700
Created October 19, 2015 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save martin9700/30181a9dbbf49bc496cb to your computer and use it in GitHub Desktop.
Save martin9700/30181a9dbbf49bc496cb to your computer and use it in GitHub Desktop.
Function Start-Log {
Param (
[int]$KeepLog = 15
)
$Script:VerbosePreference = "Continue"
$LogPath = Join-Path -Path (Split-Path $Script:MyInvocation.MyCommand.Path) -ChildPath "Logs"
If (-not (Test-Path $LogPath))
{
Try {
New-Item -Path $LogPath -ItemType Directory -ErrorAction Stop | Out-Null
}
Catch {
Write-Error "Unable to create log folder because ""$($Error[0])"", no logging will be available for this script"
Return
}
}
$LogPathName = Join-Path -Path $LogPath -ChildPath "$($Script:MyInvocation.MyCommand.Name)-$(Get-Date -Format 'MM-dd-yyyy').log"
Try {
Start-Transcript $LogPathName -Append -ErrorAction Stop
Write-Verbose "$(Get-Date): Logging for $($Script:MyInvocation.MyCommand.Name) started"
}
Catch {
Write-Error "Unable to create transcript log because ""$($Error[0])"""
Return
}
If (@(Get-ChildItem "$LogPath\*.log" | Where LastWriteTime -LT (Get-Date).AddDays(-$KeepLog)).Count -gt 0)
{
Write-Verbose "$(Get-Date): Removing old log files:"
Get-ChildItem "$LogPath\*.log" | Where LastWriteTime -LT (Get-Date).AddDays(-$KeepLog) | Remove-Item -Confirm:$false
}
}
Function Stop-Log {
Write-Verbose "$(Get-Date): Logging for $($Script:MyInvocation.MyCommand.Name) completed"
Stop-Transcript
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment