MyITGuy
10/27/2014 - 7:43 PM

PowerShell: Logging

PowerShell: Logging

#region Rotate log file every 30 days
if (Test-Path -Path $LogPath) {
    if ((Get-Item -Path $LogPath -ErrorAction SilentlyContinue).CreationTime -le (Get-Date).AddDays(-30)) {
        $LogsDirectory = [System.IO.Path]::GetDirectoryName($LogPath)
        $FileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($LogPath)
        $FileExtension = [System.IO.Path]::GetExtension($LogPath)
        $BackupFilePath = Join-Path $LogsDirectory -ChildPath "${FileNameWithoutExtension}.bak${FileExtension}"
        Remove-Item -Path $BackupFilePath -Force -ErrorAction SilentlyContinue
        Move-Item -Path $LogPath -Destination $BackupFilePath -Force -ErrorAction SilentlyContinue
        # Due to file system tunneling, when a new file is created with the name of a previously deleted file, that new file will need to have it's creation date updated.
        # This is because file system tunneling sets the creation date, for the newly created file, to that of the previously deleted file.
        # The apocryphal history of file system tunnelling, https://devblogs.microsoft.com/oldnewthing/20050715-14/?p=34923
        New-Item -Path $LogPath -ItemType File -Force -ErrorAction SilentlyContinue | Out-Null
        (Get-Item -Path $LogPath).CreationTime = (Get-Item -Path $LogPath).LastWriteTime
    }
}
else {
    New-Item -Path $LogPath -ItemType File -Force -ErrorAction SilentlyContinue | Out-Null
}
#endregion
"$([System.IO.Path]::GetFileNameWithoutExtension($script:MyInvocation.MyCommand.Name))_$(Get-Date -format "yyyyMMddhhmmss").log"
"$([System.IO.Path]::GetFileNameWithoutExtension($script:MyInvocation.MyCommand.Name)).log"
"$([System.IO.Path]::GetFileNameWithoutExtension($script:MyInvocation.MyCommand.Name))-$((Get-Date -format MMM).ToUpper()).log"
	# Log file rotation (keep last 30 logs)
	foreach ($Item In (Get-ChildItem -Path "$($PSScriptRoot)" -Filter "$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name))_*.log" | Sort LastWriteTime -Descending | Select -Skip 30)) {
		$FullName = $Item.FullName
		try {
			$Item | Remove-Item -Force -ErrorAction SilentlyContinue | Out-Null
			Write-CMTraceEvent "Removed log file. ($($FullName))"
		} catch {
			Write-CMTraceEvent -Message "$($_.Exception.InnerException.Message) ($($FullName))" -Severity Error
		}
	}
#region Logging
	$LogFilePath = "$(Split-Path $Script:MyInvocation.MyCommand.Path)\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name))-$((Get-Date -format MMM).ToUpper()).log"
	
	function Add-ToLog {
		[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="None")]
		PARAM(
			[string]
			$Message
		)	
		Add-Content -Path $LogFilePath -Value "$(Get-Date -format 'yyyy-MM-dd hh:mm:ss')$(' ' * 3)$($Message)"
	}
	Add-Content -PassThru $LogFilePath -Value ""
#endregion
#region Logging

# Start Logging
$LogFilePath = "$($env:TEMP)\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)).log"
# Log file rotation per-year
if ((Test-Path -Path $LogFilePath -PathType Container) -ne $null) {
	if ((Get-ChildItem -Path $LogFilePath).LastWriteTime.Year -ne (Get-Date).Year) {
		Move-Item -Path $LogFilePath -Destination "$LogFilePath.bak" -Force -ErrorAction SilentlyContinue | Out-Null
	}
}

function Add-ToLog {
	[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="None")]
	PARAM(
	    [string]
		$Message
	)	
	Add-Content -Path $LogFilePath -Value "$(Get-Date -format 'yyyy-MM-dd hh:mm:ss')$(' ' * 3)$($Message)"
}
#endregion