#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

About the author: Jaap Brasser

Jaap is a Senior System Engineer in the Financial Services industry. He focuses on Microsoft and related technologies and has a passion for PowerShell. In his spare time he maintains his Blog, Twitter feed, @Jaap_Brasser, and contributes on the Official Scripting Guys Forum and Windows PowerShell TechNet forums

Related Posts

%d bloggers like this: