8

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

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

为了澄清,我正在使用:

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

3 回答 3

5
function Is-Current-User-Admin
{
    return ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
于 2012-05-03T13:12:25.397 回答
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 组的成员

于 2012-05-03T13:07:32.877 回答
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}
}
于 2021-03-17T15:52:29.817 回答