Powershell – Connect to local SQL Server database via PowerShell failed with error: Named Pipes Provider, error:40

powershellsql-server-2008

Please tell me why I failed with this connection…how should I do then?

  • local machine name = MYPC
  • local instance name = MSSQLSERVER
  • my own database named mydatabase
  • I use Windows authentication to log into the local server, username = DOMAIN\mypc
  • I have no password when I log into the local server;

Lines I used are here:

$connection= new-object system.data.sqlclient.sqlconnection
$connection
$Connection.ConnectionString ="server=MSSQLSERVER;database=mydatabase;trusted_connection=false;uid=DOMAIN\mypc;"
$Connection.ConnectionString
$connection.open()

These lines failed with the following error:

Exception calling "Open" with "0" argument(s): "A network-related or
instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is
correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
At line:1 char:17
+ $connection.open <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Best Answer

A see a few problems with our connection string:

MSSQLSERVER is usually the service name for a default instance of SQL Server in which case you would use "server=MYPC" or you can use dot for the local machine "server=.". If you really have an instance name of MSSQLServer which is doubtful then your server you be "server=.\MSSQLSERVER"

When using Windows authentication i.e. trusted_connection you don't specify a uid and trusted_connection should be set to true. Here's what your connection should look like:

$Connection.ConnectionString ="server=.;database=mydatabase;trusted_connection=true;"