#This will gather the User Accounts that caused OSUninstall to fail, write to OSUninstall Log and Populate TS Variable.


try
{
    $tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
    #$tsenv.CloseProgressDialog()
}
catch
{
	Write-Verbose "Not running in a task sequence."
}


function Test-RegistryValue
{
    <# 
    .SYNOPSIS 
    Tests if a registry value exists. 
     
    .DESCRIPTION 
    The usual ways for checking if a registry value exists don't handle when a value simply has an empty or null value. This function actually checks if a key has a value with a given name. 
     
    .EXAMPLE 
    Test-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test' -Name 'Title' 
     
    Returns `True` if `hklm:\Software\Carbon\Test` contains a value named 'Title'. `False` otherwise. 
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        # The path to the registry key where the value should be set. Will be created if it doesn't exist.
        $Path,
        
        [Parameter(Mandatory=$true)]
        [string]
        # The name of the value being set.
        $Name
    )
    
    Set-StrictMode -Version 'Latest'

    #Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState

    if( -not (Test-Path -Path $Path -PathType Container) )
    {
        return $false
    }
    
    $properties = Get-ItemProperty -Path $Path 
    if( -not $properties )
    {
        return $false
    }
    
    $member = Get-Member -InputObject $properties -Name $Name
    if( $member )
    {
        return $true
    }
    else
    {
        return $false
    }
}
#region: CMTraceLog Function formats logging in CMTrace style
        function CMTraceLog {
         [CmdletBinding()]
    Param (
		    [Parameter(Mandatory=$false)]
		    $Message,
 
		    [Parameter(Mandatory=$false)]
		    $ErrorMessage,
 
		    [Parameter(Mandatory=$false)]
		    $Component = "OSUninstall",
 
		    [Parameter(Mandatory=$false)]
		    [int]$Type,
		
		    [Parameter(Mandatory=$true)]
		    $LogFile
	    )
    <#
    Type: 1 = Normal, 2 = Warning (yellow), 3 = Error (red)
    #>
	    $Time = Get-Date -Format "HH:mm:ss.ffffff"
	    $Date = Get-Date -Format "MM-dd-yyyy"
 
	    if ($ErrorMessage -ne $null) {$Type = 3}
	    if ($Component -eq $null) {$Component = " "}
	    if ($Type -eq $null) {$Type = 1}
 
	    $LogMessage = "<![LOG[$Message $ErrorMessage" + "]LOG]!><time=`"$Time`" date=`"$Date`" component=`"$Component`" context=`"`" type=`"$Type`" thread=`"`" file=`"`">"
	    $LogMessage | Out-File -Append -Encoding UTF8 -FilePath $LogFile
    }

$LogFile = "C:\ProgramData\WaaS\WaaS_OSUninstall.log" #Default if one isn't specified in Task Sequence
$ScriptName = $MyInvocation.MyCommand.Name
$CurrentBuild = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" 'ReleaseId' -ErrorAction SilentlyContinue
$RegistryPath = "HKLM:\$($tsenv.Value('RegistryPathOnline'))"
$RegistryPathFull = "$RegistryPath\$CurrentBuild"
$CustomLogPath = $tsenv.Value('CustomLogPath')
$CustomLogPreFix = $tsenv.Value('CustomLogPreFix')
if ($CustomLogPath -ne $null -and $CustomLogPath -ne "" -and $CustomLogPath -ne $null -and $CustomLogPath -ne "")
    {$LogFile = "$CustomLogPath\$($CustomLogPreFix)_OSUninstall.log"}

CMTraceLog -Message  "---Start $ScriptName---" -Type 2 -LogFile $LogFile

$Lines = Get-Content C:\windows\logs\Dism\dism.log
$NewAccounts = Foreach($line in $Lines) {
    $SecondHalf = $null
    $FirstHalf,$SecondHalf = $line -split 'not found in rollback info.',2
    if(-not [string]::IsNullOrEmpty($SecondHalf)){
        $PartWithUserName,$null = $FirstHalf -split '[(]',2
        $SplitPartWithUserName = $PartWithUserName.Split(" ")
        #$SplitPartWithUserName[$SplitPartWithUserName.Count - 1]
        $SplitUserDomain = $SplitPartWithUserName.split("\")
        $SplitUserDomain[$SplitUserDomain.Count -1]
    }
}

$NewAccounts = $NewAccounts | select -Unique
$tsenv.Value("NewAccounts") = $NewAccounts

#Record App Issue True / False
New-ItemProperty -Path $RegistryPathFull -Name "OSUninstall_Accounts" -PropertyType String -Value $NewAccounts -Force
CMTraceLog -Message  "There are $($NewAccounts.count) Accounts that have been created since upgraded to $CurrentBuild" -Type 2 -LogFile $LogFile
CMTraceLog -Message  "Please Delete $NewAccounts and try OS Uninstall Process Again" -Type 2 -LogFile $LogFile
CMTraceLog -Message  "---End $ScriptName---" -Type 2 -LogFile $LogFile