﻿
Param( 
    [parameter(Mandatory=$false)][string]$AxeCoreNet,
    [parameter(Mandatory=$false)][string]$ResultFile
)
    

# This try/finally block wraps the whole script so we can always properly dispose of objects.
#
try {


    # Need to know where our script is so we can use full path to all our dependent files.
    #
    $folderScript = Split-Path -Path $MyInvocation.MyCommand.Path -Parent

    # Try to load up Axe because it is cool.
    #
    $boolRunningUnderAxe = $false
    if ( $AxeCoreNet ) {
        $axeAssembly = [Reflection.Assembly]::LoadFrom( $AxeCoreNet )
        if ( $axeAssembly ) {
            $axeSupport = [Microsoft.Assessments.Runtime.Support]::Initialize()
            if ( $axeSupport ) {

                $boolRunningUnderAxe = $axeSupport.EngineRunning

                $axeLogger = $axeSupport.CreateLogger()
            }
        }
    }

    # This function will write what is piped to it as a string to the default output
    # (usually the host/console) and also to the log file if running under axe.
    #
    function Log-Info {
        PROCESS {
            if ( $_ ) {
                "$_" | Out-Default
                if ( $axeLogger ) {
                    $axeLogger.LogMessage( "$_" )
                }
           }
        }
    }

    # This function will write what is piped to it as a string as an error
    # and also to the log file if running under axe.
    #
    function Log-Error([int32]$ErrorCode=1) {
        PROCESS {
            if ( $_ ) {
                "$_" | Write-Error
                if ( $axeLogger ) {
                    $axeLogger.LogError( $ErrorCode, "$_" )
                }
           }dx
        }
    }


    # Create the results object from the sample in the script folder.
    #
    $xmlResults = [xml](Get-Content (Join-Path $folderScript WinsatResults.xml))
    $metrics = $xmlResults.AssessmentResult.Iterations.Iteration.MetricValues.MetricValue

    # We pull out all the metrics directly from the registry.  So this loop goes through and uses
    # the programmatic name which is the same as the registry value and populates the xml.
    #
    $missing = @()
    $metrics | % {
        $RegValue = ((Get-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows Nt\CurrentVersion\Winsat").($_.ProgrammaticName))
        if ( $RegValue -ne $null ) {
            if ( $RegValue -is [System.String] ) {
                $_.Value = $RegValue
            } else {
                # Try to make sure none of the number values we get are negative.
                #
                $_.Value = ([UInt64]$RegValue).ToString()
            }
        } else {
            # This only removes the contents of the metric value, not the actual metric value.  But
            # I was having trouble getting anything removed because powershell says it is a fixed list
            # even thought it lets me add to it.  It would have been nice if $_.ParentNode.Remove($_) worked.
            #
            #$_.RemoveAll()

            # Since removing the contents of the metric value doesn't work for Axe, we just have to keep track
            # of the ones that fail and instead of generating any metrics, generate an error.
            #
            $missing += $_.ProgrammaticName
        }
    }

    # See if any of hte metrics were missing.
    #
    if ( $missing.Count -gt 0 ) {

        $missing | % { "Missing metric: $_" | Log-Info }
        if ( $ResultFile ) {

            # This will generate an error that can be seen in WAC.
            #
            $xmlOut = [System.Xml.XmlWriter]::Create( $ResultFile )
            $xmlOut.WriteStartElement("AssessmentResult")
            $xmlOut.WriteStartElement("ErrorsAndWarnings")
            $xmlOut.WriteStartElement("Error")
            $xmlOut.WriteElementString("Hresult", "0x80070002")
            $xmlOut.WriteElementString("Message", "The following metrics are missing from HKLM:\SOFTWARE\Microsoft\Windows Nt\CurrentVersion\Winsat:  $($missing).  Please ensure WinSAT has been run on this machine by going to Performance Information and Tools in the Control Panel.")
            $xmlOut.Close()

        }

    } else {

        # The main scores should be divided by 10 so we get the right 0-9.9 value.
        #
        $AffectedMetrics = @("WinCRSScore", "CPUScore", "MemoryScore", "DWMScore", "D3DScore", "DiskScore")
        $metrics | ? { $AffectedMetrics -contains $_.ProgrammaticName } | % { $_.Value = ($_.Value / 10).ToString() }

        # These guys are integers off by 3 decimal places.
        #
        $AffectedMetrics = @("VideoMemoryBandwidth")
        $metrics | ? { $AffectedMetrics -contains $_.ProgrammaticName } | % { $_.Value = ($_.Value / 1000).ToString() }

        # These guys need to convert bytes by 1024^1.
        #
        $AffectedMetrics = @("RandomReadDiskScore")
        $metrics | ? { $AffectedMetrics -contains $_.ProgrammaticName } | % { $_.Value = ($_.Value / (1024)).ToString() }

        # These guys need to convert bytes by 1024^1.
        #
        $AffectedMetrics = @("TimeLastFormalAssessment")
        $metrics | ? { $AffectedMetrics -contains $_.ProgrammaticName } | % { $_.Value = (New-Object DateTime ([Int64]($_.Value))).AddYears(1600).ToString("u") }
    

        # Print the metrics out.
        #
        $metrics | % { "Metric $($_.ProgrammaticName)=$($_.Value)" | Log-Info }
        if ( $ResultFile ) {
            $xmlResults.Save( $ResultFile )
        }
    }


# This try/finally block wraps the whole script so we can always properly dispose of objects.
#
} finally {

    # We should always properly dispose of this guy.
    #
    if ( $axeSupport ) {
        $axeSupport.Dispose()
    }

}