Powershell检查本地管理员凭据

时间:2012-05-03 13:02:59

标签: powershell powershell-v2.0

我正在尝试运行需要管理员输入的脚本才能处理某些事情。我没有让脚本运行失败,而是试图捕获错误并将其重新放回到凭据中,但是我找不到可以将本地管理员凭据传递给陷阱的命令。有没有人有可能有用的东西?

我发现很多会检查域凭据,但这是一个LOCAL管理员帐户。

澄清一下,我正在使用:

$Cred = Get-Credential

我需要验证输出是否正确,并且具有管理员权限以在脚本中进一步运行。

工作解决方案(感谢User978511)

$Cred = Get-Credential 
$Computer = (gwmi Win32_ComputerSystem).Name
$User = $Cred.Username
$Pass = $Cred.GetNetworkCredential().Password
$Users = ("$Computer"+"$User")

Add-Type -assemblyname System.DirectoryServices.AccountManagement 
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
$DS.ValidateCredentials($Users, $pass)

if ($Result -ne "True")
{
<Perform Tasks Here>
}

3 个答案:

答案 0 :(得分:5)

function Is-Current-User-Admin
{
    return ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}

答案 1 :(得分:3)

这将返回本地管理员(另一个答案可能更适合这里):

$group =[ADSI]"WinNT://./Administrators" 
$members = @($group.psbase.Invoke("Members")) 
$admins = $members | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} 

这将检查凭证:

Add-Type -assemblyname system.DirectoryServices.accountmanagement 
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
$DS.ValidateCredentials("test", "password") 

您所要做的就是检查凭据是否正常以及该用户是Admins组的成员

答案 2 :(得分:0)

# Test Local User Account Credentials

Write-Verbose "Prompting for password" 
$pswd = Read-Host "Type password -- VERIFY BEFORE CLICKING RETURN!!!"  -assecurestring
$decodedpswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pswd))

Foreach ($computer in $computers) { 

$temp = New-Object PSobject 
         
$username = "variable with local admin user"

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine', $computer)

if ($obj.ValidateCredentials($username, $decodedpswd) -eq $True) {

Write-Host "The password of UserName $($username) in Computer $($computer) it is correct" -BackgroundColor Green}

else {

Write-Host "The password of UserName $($username) in Computer $($computer) does not is correct" -BackgroundColor Red}
}
相关问题