假设我使用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-Credential
或Test-PSCredential
是更好的名称,因为Validate
不是有效的PowerShell动词(见Get-Verb
)
答案 0 :(得分: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"
}
答案 1 :(得分:0)
我遇到与安装程序类似的问题,需要验证提供的服务帐户详细信息。我想避免在Powershell中使用AD模块,因为我不是100%这将安装在运行脚本的机器上。
我使用下面的测试进行了测试,它有点脏,但确实有效。
try{
start-process -Credential $c -FilePath ping -WindowStyle Hidden
} catch {
write-error $_.Exception.Message
break
}