简体   繁体   中英

Powershell - local credential verification

I utilized Powershell To Check Local Admin Credentials as the base for this snippet and am running into problems. (didn't want to threadjack)

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$entry)
if($pc.ValidateCredentials("secretadmin", "secretpassword")){Write-host "good"}else{write-host "bad"}

it works about 50 percent of the time. the rest of the time, i get this

Exception calling "ValidateCredentials" with "2" argument(s): "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again.

which reminds me of batch scripts using net use to verify credentials where we just needed to delete the mapped drive to fix the issue. since there is no saved object that im aware of, im unsure how to clear this logon. I checked logged on users and saw nothing

Basically, we're building hundreds of servers for hospitals and need to ensure compliance with policies, checking these credentials is just part of this but this is where i have problems.

Any help would be greatly appreciated. As a side note before these questions are asked. the credentials are correct, they're hard-coded in the script, i can receive a failure and immediately log on via RDP and psexec with the same credentials that throw the error. the firewall allows any from my host to the destination.

PrincipalContext implements IDisposable so I recommend doing this:

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

try {
    if($pc.ValidateCredentials("secretadmin", "secretpassword")) {
        Write-host "good"
    }
    else {
        Write-host "bad"
    }
}
finally {
    $pc.Dispose()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM