Skip to content

Instantly share code, notes, and snippets.

@dotps1
Last active January 5, 2024 08:23
Show Gist options
  • Select an option

  • Save dotps1/e0c70c2232b7a82df143 to your computer and use it in GitHub Desktop.

Select an option

Save dotps1/e0c70c2232b7a82df143 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Test a Domain Targeted PSCredential Object for valid Username and Password.
.DESCRIPTION
Simulates an Authentication Request in a Domain envrionment using a PSCredential Object.
Returns $true if both Username and Password pair are valid.
.EXAMPLE
Test-Credential
.NOTES
Expansion from Stack Overflow Artical: http://stackoverflow.com/questions/10802850/validating-powershell-pscredential
.LINK
http://dotps1.github.io
#>
function Test-Credential
{
[CmdletBinding()]
[OutputType([Bool])]
Param
(
# Credential, Type PSCredential, The PSCredential Object to test.
[Parameter(Position = 0,
ValueFromPipeLine = $true)]
[PSCredential]
$Credential,
# Domain, Type String, The domain name to test PSCredetianl Object against.
[Parameter(Position = 1)]
[String]
$Domain = $env:USERDOMAIN
)
Begin
{
if (-not($PSBoundParameters.ContainsValue($Credential)))
{
$Credential = Get-Credential
}
[void][System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, $Domain)
}
Process
{
$networkCredetial = $Credential.GetNetworkCredential()
return $principalContext.ValidateCredentials($networkCredetial.UserName, $networkCredetial.Password)
}
End
{
$principalContext.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment