PoshCode Archive  Artifact Content

Artifact 994d4b6abd8bb5e816a27a70aaac6674bbd43614b10f408f1d7cc4336046d064:

  • File Test-UserCredential.ps1 — part of check-in [39baccd671] at 2018-06-10 13:25:51 on branch trunk — A function to test a user’s credentials. Return true/false. Works for local or domain user accounts. (user: Andy Arismendi size: 2112)

# encoding: ascii
# api: powershell
# title: Test-UserCredential
# description: A function to test a user’s credentials. Return true/false. Works for local or domain user accounts.
# version: 0.1
# type: function
# author: Andy Arismendi
# license: CC0
# function: Test-UserCredential
# x-poshcode-id: 3449
# x-archived: 2012-06-13T22:12:18
# x-published: 2012-06-08T01:09:00
#
#
function Test-UserCredential {
	[CmdletBinding()] [OutputType([System.Boolean])]
	param(
		[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
		[System.String] $Username,

		[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
		[System.String] $Password,
		
		[Parameter()]
		[Switch] $Domain
	)
	
	Begin {
		$assembly = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement')
	}
	
	Process {
		try {
			$system = Get-WmiObject -Class Win32_ComputerSystem
			if ($Domain) {
				if (0, 2 -contains $system.DomainRole) {
					throw 'This computer is not a member of a domain.'
				} else {
					$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
				}
			} else {
				$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
			}
			
			return $principalContext.ValidateCredentials($Username, $Password)
		}
		catch {
			throw 'Failed to test user credentials. The error was: "{0}".' -f $_
		}
	}
	
	<#
		.SYNOPSIS
			Validates credentials for local or domain user.
		
		.PARAMETER  Username
			The user's username.
	
		.PARAMETER  Password
			The user's password.
	
		.EXAMPLE
			PS C:\> Test-UserCredential -Username andy -password secret
	
		.EXAMPLE
			PS C:\> Test-UserCredential -Username 'mydomain\andy' -password secret -domain

		.EXAMPLE
			PS C:\> Test-UserCredential -Username 'andy' -password secret -domain
	
		.INPUTS
			None.
	
		.OUTPUTS
			System.Boolean.
	
		.NOTES
			Revision History
				2011-08-21: Andy Arismendi - Created.	
	#>
}