Test credentials using PowerShell function

Test credentials is definitely one of the most important prerequisites when it comes to more advanced scripts. When you looping multiple remote servers and you provide wrong password in your credentials variable then your account might be locked out. Below you will find simple way to avoid such situations.

Test credentials

The Get-Credential cmdlet prompts the user for a password or a user name and password. By default, an authentication dialog box appears to prompt the user. However, in some host programs, such as the Windows PowerShell console, you can prompt the user at the command line by changing a registry entry. For more information about this registry entry, see the notes and examples. For more info go to Microsoft docs page.

Get-Credential
Get-Credential

Usage:
You can use this function in several ways. If you type Test-Cred it will ask you to provide credentials and return value “Authenticated” or “Not authenticated”:

#Type function name
Test-Cred
Test-Cred
Test-Cred
#Or save your credentials into variable and pass it from pipeline
$Credentials = Get-Credential domain\$env:username
$Credentials | Test-Cred
Test Credentials
Test Credentials

You can also load function on the beginning of the script and later use it as a one of the verification steps:

$CredCheck = $Credentials  | Test-Cred
If($CredCheck -ne "Authenticated")
{
    Write-Warning "Credential validation failed"
    pause
    Break
}

Additionaly script will break if you will not provide any input:

        Try
        {
            $Credentials = Get-Credential "domain\$env:username" -ErrorAction Stop
        }
        Catch
        {
            $ErrorMsg = $_.Exception.Message
            Write-Warning "Failed to validate credentials: $ErrorMsg "
            Pause
            Break
        }
Test-Cred error
Test-Cred error

Final script:

function Test-Cred {
          
    [CmdletBinding()]
    [OutputType([String])] 
      
    Param ( 
        [Parameter( 
            Mandatory = $false, 
            ValueFromPipeLine = $true, 
            ValueFromPipelineByPropertyName = $true
        )] 
        [Alias( 
            'PSCredential'
        )] 
        [ValidateNotNull()] 
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()] 
        $Credentials
    )
    $Domain = $null
    $Root = $null
    $Username = $null
    $Password = $null
     
    If($Credentials -eq $null)
    {
        Try
        {
            $Credentials = Get-Credential "domain\$env:username" -ErrorAction Stop
        }
        Catch
        {
            $ErrorMsg = $_.Exception.Message
            Write-Warning "Failed to validate credentials: $ErrorMsg "
            Pause
            Break
        }
    }
     
    # Checking module
    Try
    {
        # Split username and password
        $Username = $credentials.username
        $Password = $credentials.GetNetworkCredential().password
 
        # Get Domain
        $Root = "LDAP://" + ([ADSI]'').distinguishedName
        $Domain = New-Object System.DirectoryServices.DirectoryEntry($Root,$UserName,$Password)
    }
    Catch
    {
        $_.Exception.Message
        Continue
    }
 
    If(!$domain)
    {
        Write-Warning "Something went wrong"
    }
    Else
    {
        If ($domain.name -ne $null)
        {
            return "Authenticated"
        }
        Else
        {
            return "Not authenticated"
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.