验证 PowerShell PSCredential [英] Validating PowerShell PSCredential

查看:72
本文介绍了验证 PowerShell PSCredential的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a PSCrendential object in PowerShell that I created using Get-Credential.

如何根据 Active Directory 验证输入?

How can I validate the input against Active Directory ?

现在我找到了这个方法,但我觉得它有点丑:

By now I found this way, but I feel it's a bit ugly :

[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)

For future readers, please note that Test-Credential or Test-PSCredential are better names, because Validate is not a valid powershell verb (see Get-Verb)

推荐答案

我相信使用 System.DirectoryServices.AccountManagement 是不那么难看的方法:

I believe using System.DirectoryServices.AccountManagement is the less ugly way:

这是使用 ADSI(更丑?):

This is using ADSI (more ugly?):

$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"
}

这篇关于验证 PowerShell PSCredential的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆