Posted On June 14, 2020

PowerShell: Validate SQL Server Credentials

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Validate SQL Server Credentials

Add this to your SQL toolbox so that it’ll be quick and easy to validate a given MS SQL database credential before applying it to your scripts.

$id='sa'
$password='somePasswordHere'
$sqlServer='sqlServerName'
$databaseName='bookFace'
$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $id,$(ConvertTo-securestring $password -AsPlainText -Force)

function testSqlCredential {
    param(
        [Parameter(Mandatory)][string]$sqlServer,
        [Parameter(Mandatory)][pscredential]$credential,
        [string]$databaseName='master'
    )

    $ErrorActionPreference = 'Stop'

    try {
        $id = $credential.UserName
        $password = $credential.GetNetworkCredential().Password
        $connectionString = 'Data Source={0};database={1};User ID={2};Password={3}' -f $sqlServer,$databaseName,$id,$password
        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
        $sqlConnection.Open()
        $sqlConnection.Close()
        write-host "Credential is valid for $servername for database $databaseName"
        return $true
        }
    catch {
        write-warning "$error"
        return $false
        }
}

testSqlCredential $sqlServer $cred $databaseName

Leave a Reply

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

Related Post

PowerShell: Reset Active Directory User Password

# User input variables $adminUsername='intranet\kim-a' $adminPassword='SOMECOMPLEXPASSWORD' $userId='kim' $newPassword='SOMECOMPLEXPASSWORD' $domainController='intranet.kimconnect.com' # Auto-gen Variables $encryptedPassword=ConvertTo-SecureString $adminPassword -AsPlainText…

PowerShell: Microsoft Exchange Active Directory Integration

Assuming that Exchange is already set and in production, it's often advisable to record its…

PowerShell: Deploy Certs on Remote Windows Servers

Quick Script for Local Machines: $certPath="C:\kimconnect_cert.pfx" $certPlaintextPassword='PASSWORD' $certEncryptedPassword=ConvertTo-SecureString $certPlaintextPassword -AsPlainText -Force Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\My -FilePath…