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