2

#PSTip Verify local SAM store account credentials

PowerShell provides a nice way of testing if a set of credentials are correct. This can be done by using the System.DirectoryServices.AccountManagement namespace. Earlier this year Shay discussed how this class can be used to verify Active Directory credentials, PSTip Validating Active Directory user credentials. However it is also possible to verify local accounts. An example of how to test the local user account credentials:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$env:COMPUTERNAME)
$DS.ValidateCredentials('jaapbrasser', 'Secret01') 

The result of this code is a Boolean value, reporting back either True or False. To make this simpler I wrote an advanced function that verifies local user credentials. It is available in the Technet Script Repository: Test-LocalCredential

function Test-LocalCredential {
    
    [CmdletBinding()]
    
    Param
    (
        [Parameter(Mandatory=$true)]
        [string]$UserName,
        [string]$ComputerName = $env:COMPUTERNAME,
        [Parameter(Mandatory=$true)]
        [string]$Password
    ) 
    
    Add-Type -AssemblyName System.DirectoryServices.AccountManagement
    $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$ComputerName)
    $DS.ValidateCredentials($UserName, $Password)
} 

This function can be called  as shown in the next example:

PS> Test-LocalCredential -UserName jaapbrasser -Password Secret01
True
Filed in: Columns, Tips and Tricks Tags: ,

2 Responses to "#PSTip Verify local SAM store account credentials"

  1. Daniel Petcher says:

    Weirdness: I’m using this to verify a local administrator credential on a server in my domain.

    -If I supply an account that is not present among the server’s local users, the function returns $false, as expected.

    -If I supply a good account with a bad password, the function returns $false, as expected.

    -If I supply a name for a server that does not exist, I get an Exception calling “ValidateCredentials” : Network Path not found, as expected. I suppose I could handle this with Try… Catch… Finally, if needed.

    -If I supply a known-good credential, the function responds with an Exception calling “ValidateCredentials” : “Access is denied” – instead of $true.

    I’ve tried running PowerShell 5.1 on Windows 10 against Server 2008 R2 and Server 2012 R2 and Windows7, and with Windows 7 running PowerShell 5.0 against these same target servers. I get the same result everywhere.

Leave a Reply

Submit Comment

© 2017 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: