# DeployCenter - Log management # Compatible with Windows PowerShell 5.1 function Initialize-DeployCenterLogging { [CmdletBinding()] param( [AllowNull()] [string]$IPv4 = $null ) $tempRoot = [Environment]::GetEnvironmentVariable('TEMP') if ([string]::IsNullOrWhiteSpace($tempRoot)) { throw 'The TEMP environment variable is not defined.' } $script:LogRoot = Join-Path $tempRoot 'DeployCenter' if (-not (Test-Path -LiteralPath $script:LogRoot -PathType Container)) { New-Item -Path $script:LogRoot -ItemType Directory -Force -ErrorAction Stop | Out-Null } # The IPv4 address is provided by Modules\\Network.psm1. $script:LogIPv4 = $IPv4 $logIpTag = if ([string]::IsNullOrWhiteSpace($script:LogIPv4)) { 'no-ip' } else { $script:LogIPv4 -replace '[^0-9A-Za-z.-]', '_' } $script:LogFile = Join-Path $script:LogRoot ( 'DeployCenter_{0}_{1}.log' -f $logIpTag, (Get-Date -Format 'yyyyMMdd_HHmmss') ) } function Write-Log { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Message, [ValidateSet('INFO', 'SUCCESS', 'WARNING', 'ERROR')] [string]$Level = 'INFO' ) $line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message try { [System.IO.File]::AppendAllText( $script:LogFile, $line + [Environment]::NewLine, [System.Text.Encoding]::UTF8 ) } catch { # The graphical log remains available if the file cannot be accessed. } if ($null -ne $script:txtLog -and -not $script:txtLog.IsDisposed) { $script:txtLog.AppendText($line + [Environment]::NewLine) $script:txtLog.SelectionStart = $script:txtLog.TextLength $script:txtLog.ScrollToCaret() } } function Copy-DeployCenterLog { [CmdletBinding()] param( [Parameter(Mandatory=$true)][string]$DestinationRoot ) if ([string]::IsNullOrWhiteSpace([string]$script:LogFile) -or -not (Test-Path -LiteralPath $script:LogFile -PathType Leaf)) { Write-Log -Message (ConvertTo-DeployCenterLocalizedLogMessage -Message 'Log copy skipped: no log file is available.') -Level 'WARNING' return $null } try { if (-not (Test-Path -LiteralPath $DestinationRoot -PathType Container)) { throw "Destination folder is not accessible: $DestinationRoot" } $destinationPath = Join-Path $DestinationRoot ([System.IO.Path]::GetFileName($script:LogFile)) Write-Log -Message (ConvertTo-DeployCenterLocalizedLogMessage -Message "Copying the log to $destinationPath.") -Level 'INFO' Copy-Item -LiteralPath $script:LogFile -Destination $destinationPath -Force -ErrorAction Stop | Out-Null return $destinationPath } catch { Write-Log -Message (ConvertTo-DeployCenterLocalizedLogMessage -Message "Unable to copy the log to '$DestinationRoot' : $($_.Exception.Message)") -Level 'WARNING' return $null } }