Log.ps1


#
# Logging
#

$Global:LogFile = $null
$Global:LogVerbose = $False

Function Convert-ObjectToHashtable([psobject]$object) { 
    $output = @{}

    $object.PSObject.Properties | ForEach-Object {
        if ($_.Value -is [PSCustomObject]) {
            $_.Value = Convert-ObjectToHashtable($_.Value)
        }
        $output.($_.Name) = $_.Value
    } 

    return $output
}

Function Convert-ArrayToString([array] $array)
{
    return "[" + (
        $array.foreach(
            {
                if ($_ -is [PSCustomObject]) {
                    "$(Convert-HashToString( Convert-ObjectToHashtable $_))"
                }
                elseif ($_ -is [hashtable])
                {
                    "$(Convert-HashToString $_)"
                }
                elseif ($_ -is [array])
                {
                    "$(Convert-ArrayToString $_)"
                }
                else
                {
                    "$_"
                }
            }) -join ', ') + "]"
}

Function Convert-HashToString([psobject]$hashtable) {
    return "@{" + (
        $hashtable.keys.foreach(
            {
                $value = $hashtable[$_]
                if ($value -is [hashtable])
                {
                    "$_=$(Convert-HashToString $value)"
                }
                elseif ($value -is [array])
                {
                    "$_=$(Convert-ArrayToString $value)"                    
                }
                else
                {
                    "$_=$value"                    
                }
            }) -join ', '
        ) + "}"
}

Function LogInit([string]$logDir, [string]$logFile, [bool]$overwrite, [bool]$Verbose) {
    if ([string]::IsNullOrEmpty($logDir)) {
        $Global:LogFile = "$(Get-Location)\$logFile"
    } else {
        $Global:LogFile = "$logDir\$logFile"
    }
    $Global:LogVerbose = $Verbose
    if ($overwrite) {
        $timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffffZ")
        "$($timestamp): New log" | Out-File -FilePath $Global:LogFile
    } else {
        $timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffffZ")
        "$($timestamp): New log" | Out-File -FilePath $Global:LogFile -Append
    }
    Write-Host "Logging to $($Global:LogFile) Verbose $Verbose"
}

Function LogIt([string]$message, [bool]$echoToScreen = $True) {
    if ($echoToScreen) {
        Write-Host $message
    }
    $timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffffZ")
    "$($timestamp): $message" | Out-File -FilePath $Global:LogFile -Append
}

Function LogFatal([string]$message, [bool]$echoToScreen = $True) {
    LogIt $message $echoToScreen
    throw $message
}