Connect to SQL Server using powershell

I use this powershell script below to connect to an sql server instance. I am sure my username and password are correct.

$ connectionString = "server = {0}; database = {1}; uid = {2}; pwd = {3};"

$c = Get-Credential
Write-Host($ipAddress)
Write-Host  $c.username 
Write-Host  $c.GetNetworkCredential().password

$connectionString = [string]::Format( "server={0};database={1};uid={2};pwd={3};", "servername", "databasename",$c.username,$c.GetNetworkCredential().password) 
#open database connection to SQL Server

Write-Host  $connectionString
$conn = New-Object system.Data.SqlClient.SqlConnection
$conn.connectionstring = $connectionString
$conn.open

    switch ($conn.State)
{
"Open" { Write-Host "Do some work"; }
Default { Write-Host "The connection is $($conn.State).  There has been an error connecting to the database."; }
}

This always applies to the default statement.

+5
source share
1 answer

Your call to $ conn.open is missing (), so it will return a reference to this method, not call it.

+4
source

All Articles