11

假设我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

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

4

2 回答 2

9

我相信使用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"
}
于 2012-05-29T16:33:00.490 回答
2

我在安装程序时遇到了类似的问题,需要验证提供的服务帐户详细信息。我想避免在 Powershell 中使用 AD 模块,因为我不是 100% 会安装在运行脚本的机器上。

我使用下面的方法进行了测试,它有点脏,但确实有效。

try{
    start-process -Credential $c -FilePath ping -WindowStyle Hidden
} catch {
    write-error $_.Exception.Message
    break
}
于 2017-05-26T07:53:27.717 回答