如何比较用户输入的用户名和密码与AD组?

时间:2016-03-17 06:29:12

标签: powershell active-directory

假设我询问用户的用户名和密码,如何将该数据与AD组进行比较以确保该用户是某个组的成员,并且该用户是否为其帐户输入了正确的密码?我打算创建一个只允许组成员使用该工具的工具。

$Username = Read-Host 'What is your username?'

Param(
    [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
    [SecureString]$password
)

$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

1 个答案:

答案 0 :(得分:0)

*假设您使用的是ActiveDirectory模块

验证用户是否是AD群组的成员:

$Username = Read-Host 'What is your username?'
$Group = "Your AD Group name"
$ADUser = Get-ADUser $Username

If ($ADUser)
{
    $ADGroup = Get-ADGroupMember $Group
    if ($ADUser.SamAccountName -in ($ADGroup.SamAccountName))
    {
       "Exist"
    }
    else
    {
       "Not Exist"
    }
}

针对域控制器验证AD用户凭据:

*不需要AD模块

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$Username = Read-Host 'What is your username?'
$Password = Read-Host 'What is your Password?'
$Domain = Read-Host 'What is your DOMAIN Name?'

$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct, $Domain
if ($pc.ValidateCredentials($UserName, $Password))
{
    "Validated"
}

Else
{
    "Invalid Credential"
}