function Test-ADCredential {
    [CmdletBinding()]
    Param
    (
        [string]$UserName,
        [string]$Password
    )
    if (!($UserName) -or !($Password)) {
        
		$false
    } else {
        Add-Type -AssemblyName System.DirectoryServices.AccountManagement
		#Lets figure out is its a upn or lebacy style account
		if ($UserName.contains("@"))
		{
			$arUserName = $UserName -split "@"
			$Domain = $arUserName[1]
			$UserNameRight = $arUserName[0]
		}
		else
		{
			$arUserName = $UserName -split "\\"
			$Domain = $arUserName[0]
			$UserNameRight = $arUserName[1]
		}
		
		if ($Domain -eq $null)
		{
			Write-Warning "No Domain was included.  Please run again"
			Write-Host "Sleeping for 5 seconds"
			sleep 5
			Write-Host "Exting Script"
			sleep 1
			exit
		}
		
		
		$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
		$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain 
		if (!$?)
		{
			Write-Warning "Could not contact Domain Controller for Domain [$Domain].  Please run again"
			Write-Host "Sleeping for 5 seconds"
			sleep 5
			Write-Host "Exting Script"
			sleep 1
			exit
		}
		$pc.ValidateCredentials($UserNameRight,$Password)
    }
}

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

$ScriptPath = Get-ScriptDirectory
$credential = Get-Credential
if ($credential.UserName -eq $null)
{
	Write-Host "No Account was specified.  Please run again!"
	exit
}
$MyCredPW = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($credential.Password))
$MyUserName =$credential.UserName
if (!($MyUserName) -or !($MyCredPW)) 
{
	Write-Warning 'Must enter both a user name and password.  Please run again'
	Sleep 5
	Exit
}

Write-Host "==================================="
Write-Host "   Testing supplied password for account [$MyUserName]       "
Write-Host "==================================="
$test = Test-ADCredential $MyUserName $MyCredPW
if ($test)
{
	Write-Host "Password test for account [$MyUserName] Passed!"
	Sleep 2
}
else
{
	Write-Warning "Password test for account [$MyUserName] Failed.  Please try again"
	Sleep 5
	exit
}
$credential | Export-CliXml -Path "$ScriptPath\..\config\cred.xml"
