Public/Test-MDSADAuthentication.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Function Test-MDSADAuthentication {
    <#
    .SYNOPSIS
    Validate Active Directory credentials

    .DESCRIPTION
    Validate Active Directory credentials

    .EXAMPLE
    Test-MDSADAuthentication -Credential MyUserName

    Prompt for credentials for username MyUserName and validate the credentials with Active Directory

    .EXAMPLE
    Test-MDSADAuthentication -Credential MyUserName -DomainController MyDC01

    Prompt for credentials for username MyUserName and validate the credentials with Active Directory on a specified domain controller

    .NOTES
    The Confirm parameter is prompted by default due to the chance of locking out accounts.

    #>


    #requires -Module ActiveDirectory

    [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingPlainTextForPassword', '')]
    [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUsePSCredentialType', '')]

    [CmdletBinding(
        SupportsShouldProcess=$True,
        ConfirmImpact='High'
    )]

    Param(
        [parameter(Position=0,Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [parameter(Position=1)]
        $DomainController
    )

    Try {
        If ($null -ne $PSBoundParameters.DomainController) {
            $DomainControllerDN = Get-ADDomainController $DomainController -ErrorAction Stop |
                Select-Object -ExpandProperty ComputerObjectDN
            $LDAPPath = "LDAP://{0}" -f $DomainControllerDN
        }

        If ($PSCmdlet.ShouldProcess($Credential.UserName,$MyInvocation.MyCommand)) {
            $null -ne (New-Object DirectoryServices.DirectoryEntry "$($LDAPPath)",$Credential.UserName,$Credential.GetNetworkCredential().Password).psbase.name
        }
    }
    Catch {
        Write-Error $PSItem
    }
}