<#
Copyright (c) 2015, Adam Beardwood
All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 
 
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>

#Requires -version 3

<#
.SYNOPSIS
	Deletes Remote User Profile
.DESCRIPTION
    Invokes WMI method to delete remote user profile - now with GUI!
.EXAMPLE
    C:\>Delete-RemoteProfileUI.ps1
.NOTES
    Author: Adam Beardwood
    Date: May 19, 2015
	v1.0: Initial Release
	v1.1: Added support for handling .old/.bak SIDs
#>

write-verbose "Load XAML for WPF"

$xaml=@"
<Window x:Name="Main"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Remote Profile Deleter" Height="400" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="13*"/>
            <ColumnDefinition Width="60*"/>
        </Grid.ColumnDefinitions>
        <TextBox Name="computername_txt" HorizontalAlignment="Left" Height="23" Margin="65,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="150" Grid.Column="1"/>
        <TextBox Name="username_txt" HorizontalAlignment="Left" Height="23" Margin="65,47,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="150" Grid.Column="1"/>
        <Button Name="find_btn" Content="Find" HorizontalAlignment="Left" Margin="55,91,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1" Height="22"/>
        <Label Content="Computername" HorizontalAlignment="Left" Margin="10,8,0,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Width="100" Height="26"/>
        <Label Content="Username" HorizontalAlignment="Left" Margin="10,45,0,0" VerticalAlignment="Top" Width="100" Grid.ColumnSpan="2" Height="26"/>
        <TextBlock Name="result_txt" HorizontalAlignment="Left" Margin="10,130,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="160" Width="272"/>
        <Button Name="delete_btn" Content="Delete" Grid.Column="1" HorizontalAlignment="Left" Margin="20,316,0,0" VerticalAlignment="Top" Width="75"/>
        <CheckBox Name="confirm_chk" Content="Confirm" Grid.Column="1" HorizontalAlignment="Left" Margin="112,319,0,0" VerticalAlignment="Top"/>

    </Grid>
</Window>
"@

[xml]$xmlWPF = $xaml

try{
	Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
}catch{
	Throw "Failed to load Windows Presentation Framework assemblies."
}

$xamGUI = [Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

$xmlWPF.SelectNodes("//*[@Name]") | %{
	Set-Variable -Name ($_.Name) -Value $xamGUI.FindName($_.Name) -Scope Global
}

write-verbose "Create Event Handlers"

$find_btn.add_Click({

	write-verbose "Reset UI to default"
	$result_txt.text = $null
	$confirm_chk.Background="White" 
	$confirm_chk.BorderBrush="#FF8E8F8F"
	$confirm_chk.Foreground="Black"
	$confirm_chk.IsChecked = $False

	$computername = $computername_txt.text
	$username = $username_txt.text
	
	if(($computername -ne "") -and ($username -ne "")){

		write-verbose "Get profile info from remote machine"
		if(Test-Connection $computername -q -count 1){
			$global:usrprofile = gwmi Win32_UserProfile -ComputerName $computername -Credential $cred | ?{$_.localpath -eq "C:\users\$username"}
		 
			if($usrprofile -eq $null){
				write-verbose "No matching profiles found on $computername"
				$result_txt.text = "No matching profiles found on: $computername"
			}else{
				foreach($prof in $usrprofile){
					$sid = $prof.sid
					$status = $prof.status
					if($sid -match "^S-1(-\d+){1,6}$"){
						write-verbose "Convert profile sids into friendly names"
						$result_txt.text += "$((New-Object System.Security.Principal.SecurityIdentifier($sid)).Translate([System.Security.Principal.NTAccount]).Value) - $($prof.status)`n"
					}elseif($sid -match "^S-1(-\d+){1,6}\.\w{3}$"){
						write-verbose "Profile SID is a .old or .bak"
						$sid = $($sid -split ".")[0]
						$result_txt.text += ".old or .bak SID Profile - $((New-Object System.Security.Principal.SecurityIdentifier($sid)).Translate([System.Security.Principal.NTAccount]).Value) - $($prof.status)`n"
					}else{
						write-verbose "Something other than a SID was passed"
						$result_txt.text += "SID was not passed in a valid format"
					}
				}
			}
		}else{
			write-verbose "Computer unreachable"
			$result_txt.text = "Unable to contact $computername"
		}
	}else{
		write-verbose "Missing user or computer name"
		$result_txt.text = "You must provide both a username and computername"
	}
	
	write-verbose "Clear User/Computername variables"
	rv computername,username
})

$delete_btn.add_Click({

	if($usrprofile -eq $null){
	}else{
		if($confirm_chk.IsChecked -eq $true){
			write-verbose "Delete profiles and reset UI to default"
			$usrprofile.delete()
			$result_txt.text = "Profiles Deleted"
			$usrprofile = $null
			$confirm_chk.IsChecked = $False
			$confirm_chk.Background="White" 
			$confirm_chk.BorderBrush="#FF8E8F8F"
			$confirm_chk.Foreground="Black"
		}else{
			write-verbose "Highlight Confirm box in red"
			$confirm_chk.Background="Red" 
			$confirm_chk.BorderBrush="Red" 
			$confirm_chk.Foreground="Red"
		}
	}
})

write-verbose "Launch UI"
$cred = $null
while($cred -eq $null){
	$cred = get-credential -Message "Please enter admin credentials for the target machine"
}
$xamGUI.ShowDialog() | out-null
$xamGUI.Activate() | out-null
