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.

$cred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $id,$(ConvertTo-securestring $password -AsPlainText -Force)

function testSqlCredential {

    $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
        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 *