验证PowerShell PSCredential

Ste*_*e B 10 security powershell

假设我PSCrendential在PowerShell中创建了一个使用的对象Get-Credential.

如何验证针对Active Directory的输入?

到现在为止我找到了这种方式,但我觉得它有点难看:

[void][System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")


function Validate-Credentials([System.Management.Automation.PSCredential]$credentials)
{
    $pctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, "domain")
    $nc = $credentials.GetNetworkCredential()
    return $pctx.ValidateCredentials($nc.UserName, $nc.Password)
}

$credentials = Get-Credential

Validate-Credentials $credentials
Run Code Online (Sandbox Code Playgroud)

[编辑,两年后]对于未来的读者,请注意Test-Credential或者Test-PSCredential是更好的名称,因为Validate它不是有效的powershell动词(请参阅参考资料Get-Verb)

CB.*_*CB. 8

我认为使用System.DirectoryServices.AccountManagement是不那么丑陋的方式:

这是使用ADSI(更丑陋?):

$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password

# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)

if ($domain.name -eq $null)
{
 write-host "Authentication failed - please verify your username and password."
 exit #terminate the script.
}
else
{
 write-host "Successfully authenticated with domain $domain.name"
}
Run Code Online (Sandbox Code Playgroud)