Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
driz Avatar asked Jul 06 '26 03:07

driz


1 Answers

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()
}
like image 196
Keith Hill Avatar answered Jul 07 '26 21:07

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!