#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 {

        [string]$ComputerName = $env:COMPUTERNAME,

    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
Share on: