Public/Write-Log.ps1
function Write-Log { [CmdletBinding(PositionalBinding=$true)] param ( [Parameter(Mandatory=$false)][string]$LogText, [Parameter(Mandatory=$false)][ValidateSet('error', 'normal', 'warning')][string]$LogType = 'normal', [Parameter(Mandatory=$false)][string]$LogFolderPath = $Global:LogPath, [Parameter(Mandatory=$false)][Object]$ErrorObject, [Parameter(Mandatory=$false)][String]$FunctionName ) $dateTime = (Get-Date).ToString('s') $user = $env:USERNAME if ($user.Length -lt 1) { $user = $env:USER } $logFilePath = "$LogFolderPath/$LogType.log" if ($PSBoundParameters.Keys -notcontains "FunctionName") { $functionName = (Get-PSCallStack)[1].Command } if ($LogType -eq 'error' -or $ErrorObject -ne $null) { $logColor = 'Magenta' $errorResponse = '' try { $streamReader = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()) $ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json $streamReader.Close() if ($ErrResp.error.message.Length -gt 1) { $errorResponse = " :: ErrResponse: $($ErrResp.error.message)" } } catch { } $logMsg = "$dateTime :: $user :: $functionName :: type=$LogType :: $LogText$errorResponse :: ErrorMessage: ""$($ErrorObject.Exception.Message -replace '\r|\n', ' ')"" :: Error Details: ""$($ErrorObject.ErrorDetails.Message -replace '\r|\n', ' ')"" :: StackTrace: ""$($ErrorObject.ScriptStackTrace -replace '\r|\n', ' ')""" } elseif ($LogType -eq 'warning') { $logColor = 'Yellow' $logMsg = "$dateTime :: $user :: $functionName :: type=$LogType :: $LogText" } else { $logColor = 'Cyan' $logMsg = "$dateTime :: $user :: $functionName :: type=$LogType :: $LogText" } Write-Host -ForegroundColor $logColor $logMsg try { $logMsg | Out-File $logFilePath -Append } catch { Write-Host -ForegroundColor Red "Error logging message to "$LogFilePath" Message: $($_.Exception.Message)" } } |