检查用户密码input在Powershell脚本中是否有效

我正在使用Powershell脚本,将计划任务添加到我们域中的系统。 当我运行这个脚本时,它会提示我input密码。 我有时会用手指敲一下密码,这个过程就开始了,锁住了我的账户。 有没有办法来validation我的凭据,以确保我input的内容将与域validation?

我想find一种方法来查询域控制器。 我做了一些Googlesearch,我应该可以做一个WMI查询和陷阱的错误。 如果可能,我想避免这种validation方式。

有任何想法吗? 提前致谢。

我在我的图书馆有这个:

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

这是我以前用过的; 它应该适用于本地计算机帐户和“应用程序目录”,但到目前为止,我只用它成功与AD凭据:

  function Test-Credential { <# .SYNOPSIS Takes a PSCredential object and validates it against the domain (or local machine, or ADAM instance). .PARAMETER cred A PScredential object with the username/password you wish to test. Typically this is generated using the Get-Credential cmdlet. Accepts pipeline input. .PARAMETER context An optional parameter specifying what type of credential this is. Possible values are 'Domain','Machine',and 'ApplicationDirectory.' The default is 'Domain.' .OUTPUTS A boolean, indicating whether the credentials were successfully validated. #> param( [parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Management.Automation.PSCredential]$credential, [parameter()][validateset('Domain','Machine','ApplicationDirectory')] [string]$context = 'Domain' ) begin { Add-Type -assemblyname system.DirectoryServices.accountmanagement $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::$context) } process { $DS.ValidateCredentials($credential.UserName, $credential.GetNetworkCredential().password) } } 

我发现这个post很有用,但它并没有解决我的问题,因为我试图从本地pipe理员帐户login的脚本运行它。 它似乎没有作为本地pipe理员(只有当作为域用户login)。

然而,我终于设法得到一个工作的解决scheme,既然这是很麻烦,我想我会在这里分享,所以与这个问题的其他人将在这里得到答案。 这两个答案都取决于你的需求。

请注意,在scipt(不包括在这里,因为这只是获取凭证部分)较高,powergui已安装,是下面的代码(以及“Add-PSSnapin Quest.ActiveRoles.ADManagement”行)的要求。 不知道什么powergui这是不同的,但没有人能告诉我,它的工作原理。

在“domain_name”部分中replace您自己的域名。

 #Get credentials $credential_ok = 0 while ($credential_ok -ne 1) { $credential = get-credential $result = connect-qadservice -service *domain_name* -credential $credential [string]$result_string = $result.domain if ($result_string -eq "*domain_name*") { $credential_ok = 1 #authenticated } else { #failed } } $username = $credential.username $password = $credential.GetNetworkCredential().password $date = get-date Add-Content "c:\lbin\Install_log.txt" "Successfully authenticated XP script as $username $date"