Created
October 19, 2015 15:27
-
-
Save martin9700/30181a9dbbf49bc496cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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