          [DateTime] $datetime = [DateTime]::FromFileTimeUTC($_.ClockTime).ToLocalTime()

                    # convert hex string to decimals
                    $processId = $_.PID -as [int]
                    $threadId = $_.TID -as [int]

                    # Log columns:
                    # Time ProcessID ThreadID Component Message
                    $writer.WriteLine("$($datetime.ToString($TIMESTAMP_FORMAT)) $($processId.ToString().PadRight(5)) $($threadId.ToString().PadRight(5)) $($_.EventName.PadRight(15)) $($_.UserData)")
                }
            }
            catch
            {
                # Log exception, eat it, and process the rest of the log.
                Write-Warning "Unable to process line $lineNum."

                "Unable to process line:$lineNum of $CsvPath`n$row`n$_`n---" | Out-File $DEBUG_LOG_PATH -Encoding ascii -Append
            }

            $lineNum++
        } # foreach
    }
    finally
    {
        $writer.Close()
    }

    Write-Verbose "Done. Elapsed: $((Get-Date).Subtract($start).TotalMilliseconds) ms."
}

function FlushWindowsUpdateETLs
{
    Write-Verbose "Flushing Windows Update ETLs ..."

    Stop-Service usosvc -ErrorAction Stop
    Stop-Service wuauserv -ErrorAction Stop

    Write-Verbose "Done."
}

#
# Given an ETL path, convert the ETL file(s) into text log.
#
function ConvertETLsToLog
{
    Param(
        [string[]] $ETLPaths = $(throw "'etlPaths' parameter is required."),
        [string] $LogPath = $(throw "'LogPath' parameter is required."),
        [ValidateSet('XML', 'CSV')] $Type = $(throw "'type' parameter is required.")
    )

    if ($ETLPaths.Count -gt 1)
    {
        "`nMerging and converting $($ETLPaths.Count) ETLs into $LogPath ..." | Out-Default
    }
    elseif ($ETLPaths.Count -eq 1)
    {
        "`nConverting $($ETLPaths[0]) into $LogPath ..." | Out-Default
    }
    else
    {
        throw "No Windows Update ETL file found."
    }

    $start = Get-Date

    [System.Collections.Generic.List[System.String]] $etlList = GetListOfETLs -path $ETLPaths
    # Create Working Directory
    New-Item -Path $WORKDIR -ItemType Directory -ErrorAction SilentlyContinue | Out-Null

    $tempFilePath = "$WORKDIR\wuetl.$Type.tmp"
    $tempLogPath = "$WORKDIR\wuetl.log.tmp"

    Remove-Item "$tempFilePath.*" -Force -ErrorAction SilentlyContinue | Out-Null
    Remove-Item "$tempLogPath.*" -Force -ErrorAction SilentlyContinue | Out-Null
    Remove-Item $DEBUG_LOG_PATH -Force -ErrorAction SilentlyContinue | Out-Null

    $processed = 0;
    $tempFileCount = 0
    
    # Pad tempFileCount so files can be sorted numerically.
    $NumFormat = "{0:00000}"

    while ($processed -lt $etlList.Count)
    {
        $remaining = $etlList.Count - $processed

        $numberedTempFile = "$tempFilePath.$NumFormat" -f $tempFileCount
        $numberedLogFile = "$tempLogPath.$NumFormat" -f $tempFileCount

        if ($remaining -ge $MAX_ETL_PER_BATCH)
        {
            DecodeETL -ETLList $etlList.GetRange($processed, $MAX_ETL_PER_BATCH) -OutPath $numberedTempFile -Type $Type
            $processed += $MAX_ETL_PER_BATCH
        }
        else
        {
            DecodeETL -ETLList $etlList.GetRange($processed, $remaining) -OutPath $numberedTempFile -Type $Type
            $processed += $remaining
        }       

        if ($Type -eq 'XML')
        {
            ConvertXmlToLog -XmlPath $numberedTempFile -LogPath $numberedLogFile
        }
        else
        {
            ConvertCsvToLog -CsvPath $numberedTempFile -LogPath $numberedLogFile
        }

        $tempFileCount++
    }

    if ($tempFileCount -gt 1)
    {
        Write-Verbose "Merging all temporary logs into one ..."
        Get-Content "$tempLogPath.*" | Out-File $LogPath -Encoding ascii
    }
    else
    {
        $src = "$tempLogPath.$NumFormat" -f 0
        Copy-Item -Path $src -Destination $LogPath -ErrorAction Stop
    }

    # Not removing $tempFilePath.* so users can use XML/CSVs to do more fancy stuff should they wish.
    Remove-Item "$tempLogPath.*" -ErrorAction SilentlyContinue | Out-Null

    Write-Verbose "Total elapsed: $((Get-Date).Subtract($start).TotalMilliseconds) ms."

    "`nWindowsUpdate.log written to $LogPath`n" | Out-Default
}

#.ExternalHelp WindowsUpdateLog.psm1-help.xml
function Get-WindowsUpdateLog
{
    [CmdLetBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'High')]
    Param(
        [parameter(
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0)]
        [Alias('PsPath')]
        [string[]] $ETLPath = @("$env:windir\logs\WindowsUpdate"),

        [parameter(
            Position = 1)]
        [string] $LogPath = "$([System.Environment]::GetFolderPath("Desktop"))\WindowsUpdate.log",

        [ValidateSet('CSV', 'XML')]
        [string] $ProcessingType = 'CSV',

        [switch] $ForceFlush
    )

    begin
    {
        $etls = New-Object System.Collections.ArrayList
    }

    process
    {
        #
        # Handles pipeline input. For e.g. get-childitem C:\temp | get-windowsupdatelog
        #
        if ($_ -ne $null)
        {
            if ($_.PsPath -eq $null -or !(Test-Path $_.PsPath))
            {
                throw "ETL file cannot be found or is invalid: $_"
            }
            
            $etls.Add($_.FullName) | Out-Null
        }
        #
        # Handles regular input. For e.g. get-windowsupdate.log C:\temp\WindowsUpdate1.etl, C:\temp\WindowsUpdate2.etl
        #
        else
        {
            foreach ($p in $ETLPath)
            {
                if (!(Test-Path $p))
                {
                    throw "File not found: $p"
                }
                $etls.Add($p) | Out-Null
            }
        }
    }

    end
    {
        if ($ForceFlush)
        {
            if ($PSCmdlet.ShouldProcess("$env:COMPUTERNAME", "Stopping Update Orchestrator and Windows Update services"))
            {
                FlushWindowsUpdateETLs
            }
            else
            {
                return
            }
        }

        # The rest of the function doesn't support -WhatIf, so just bail out if -WhatIf is specified
        if ($WhatIfPreference)
        {
            return
        }

        #
        # Make sure we have permission to write log file to requested path.
        #
        $logDir = Split-Path -Parent $LogPath

        if (!(Test-Path $logDir))
        {
            New-Item -Path $logDir -ErrorAction Stop
        }

        try
        {
            "Checking write access" | Out-File -FilePath $LogPath -Encoding ascii
        }
        catch [System.UnauthorizedAccessException]
        {
            throw "No permission to write to $LogPath"
        }

        #
        # Do work now.
        #

        ConvertETLsToLog -ETLPaths $etls -LogPath $LogPath -Type $ProcessingType
    }
}

Export-ModuleMember -Function Get-WindowsUpdateLog
