Search code examples
powershellpowershell-2.0

Powershell To Check Local Admin Credentials


I'm trying to run a script that requires Administrator input in order to process certain things. Rather than have the script run unsuccessfully I'm trying to trap the error and throw it back into the Credentials, but I can't find a command I can pass Local Admin Credentials with to a Trap. Does anyone have anything that might work?

I've found MANY that will check domain credentials, but this is a LOCAL Admin account.

To clarify, I am using:

$Cred = Get-Credential

I need to verify the output from that is correct and has Admin access to run stuff further down in the script.

Working Solution (Thanks to 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>
}

Solution

  • This will return you local admins (another answer is probably better fit here):

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

    And this will check credentials:

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

    All you have to do is to check that credentials are ok and that user is member of Admins group