Jump to content
Sign in to follow this  
support

Validate Password for SQL Account (by Click Studios)

Recommended Posts

Script Name

Validate Password for SQL Account

 

Description

Checks if a SQL Account Password is correct

 

System Requirements

  • Firewall to allow access

 

Successfully Tested Against

  • SQL Server 2005, 2008, 2012, 2014
  • And express editions

 

Failed Testing Against

  • None reported 

 
PowerShell Script

<#
.SYNOPSIS
Connect to a Microsoft SQL server and validates the password for a local SQL account.
.NOTES
Requires database connections on in-use Port to be allowed through Firewall
#>
function Validate-SQLPassword
{
	[CmdletBinding()]
	param (
		[String]$HostName,
		[String]$InstanceName,
		[String]$SQLPort,
		[String]$UserName,
		[String]$CurrentPassword
	)

	try
	{
		#Declare some connection string variables
		[String]$InstanceNameString = ''
		[String]$SQLPortString = ''
		
		#Construct the Instance Name section of the connection string if required
		if ($InstanceName -ne '') {
			$InstanceNameString = '\' + $InstanceName
		}
		
		#Construct the Port Number section of the connection string if required
		if ($SQLPort -ne '') {
			$SQLPortString = ',' + $SQLPort
		}
		
		$SQLConnection = New-Object System.Data.SqlClient.SqlConnection
		$SQLConnection.ConnectionString = "Server=" + $HostName + $InstanceNameString + $SQLPortString + ";User ID=" + $UserName + ";Password=" + $CurrentPassword + ";"
		$SQLConnection.Open()
		$SQLConnection.Close()
		Write-Output "Success"
	}
	catch
	{
		switch -wildcard ($error[0].Exception.ToString().ToLower())
		{
			"*A network-related or instance-specific*" { Write-Output "Failed to execute script correctly against Host '$HostName' for the account '$UserName'. Please check SQL details are correct, and that a firewall is not blocking access - default Port is 1433."; break }
			"*Login failed for user*" { Write-Output "Failed to validate the password for the SQL account '$UserName' on Host '$HostName'. UserName or Password is incorrect."; break }
			#Add other wildcard matches here as required
			default { Write-Output "Failed to validate the password for the SQL account '$UserName' on Host '$HostName'. Error = " + $error[0].Exception }
		}
	}
}

#Make a call to the Validate-SQLPassword function
Validate-SQLPassword -HostName '[HostName]' -InstanceName '[SQLInstanceName]' -SQLPort '[DatabasePort]' -Username '[UserName]' -CurrentPassword '[CurrentPassword]'

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×