2012-05-29 35 views
9

比方说,我使用Get-Credential在PowerShell中创建了一个PSCrendential对象。验证PowerShell PSCredential

如何根据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-CredentialTest-PSCredential更好的名字,因为Validate不是有效的PowerShell动词(见Get-Verb

回答

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" 
} 
+0

据我所知,PSCredentials是身份验证提供程序不可知论(它基本上是一个简单的用户名/密码容器),但这个要求听起来很常见。 –

+0

@SteveB对于系统管理员和开发人员来说,这是一个非常常见的任务,尤其是那些在AD工作的人员,这就是为什么(IMO)微软需要AccountManagement。在这里你可以看到在c#中使用多种方式来完成这个任务:http://stackoverflow.com/questions/290548/c-sharp-validate-a-username-and-password-against-active-directory –

+0

事实上,一般开发最佳实践适用于此。特别是我可以隐藏在这个功能的复杂性,然后简单地调用函数:) –

0

我是有一个安装了类似的问题,并核实所提供的服务帐户的细节要求。我想避免在Powershell中使用AD模块,因为我不是100%,这将安装在运行脚本的机器上。

我做了下面的测试,它有点脏,但它确实有效。

try{ 
    start-process -Credential $c -FilePath ping -WindowStyle Hidden 
} catch { 
    write-error $_.Exception.Message 
    break 
} 
+1

既不是我的问题也不@cb。答案要求加载AD模块。它实际上依赖于与AD相关的一些.Net类,这些类始终可用于PowerShell。 –