How to connect to SQL Server LocalDB using Invoke-Sqlcmd?

Gian Marco picture Gian Marco · Jun 13, 2013 · Viewed 10.1k times · Source

I have sqlcmd.exe from both SQLServer 2008 and SQLServer 2012:

PS C:\> Get-Command sqlcmd.exe

Definition
----------
C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE
C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE

By modifying $env:PATH i force the use of sqlcmd.exe from SQL Server 2012:

PS C:\> $env:PATH = ($env:PATH -split ";" | Where-Object { $_ -notlike "*\Microsoft SQL Server\100\*" }) -join ";"
PS C:\> Get-Command sqlcmd.exe

Definition
----------
C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE

The default instance of LocalDB is up and running, and owned by the current user:

PS C:\> sqllocaldb i v11.0
Name:               v11.0
Version:            11.0.2318.0
Shared name:
Owner:              DOMAIN\me
Auto-create:        Yes
State:              Running
Last start time:    12/06/13 18:17:57
Instance pipe name: np:\\.\pipe\LOCALDB#08EDBEF0\tsql\query

Now, i can execute command on (localdb)\v11.0 using sqlcmd.exe

PS C:\> sqlcmd.exe -S "(localdb)\v11.0" -Q "select 1"

-----------
          1

But when trying the same with Invoke-Sqlcmd i get a connection error:

PS C:\> Import-Module sqlps
PS C:\> Invoke-Sqlcmd -ServerInstance "(localdb)\v11.0" -Query "select 1"
Invoke-Sqlcmd : 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

What can i do to lmake Invoke-Sqlcmd connect to (localdb)\v11.0 ?

Answer

user2681363 picture user2681363 · Oct 4, 2013

Got this from a couple other sources, seems to work so far.

JBs Powershell

and

How can I run PowerShell with the .NET 4 runtime?

Another way of making PowerShell and LocalDB play nice is to make PowerShell aware of DOTNET 4.0.3. This can be done by creating a file called "powershell.exe.config" in the C:\Windows\System32\WindowsPowerShell\v1.0 . The file should contain the following:

<?xml version="1.0"?>
<configuration> 
     <startup useLegacyV2RuntimeActivationPolicy="true"> 
          <supportedRuntime version="v4.0.30319"/> 
          <supportedRuntime version="v2.0.50727"/> 
     </startup> 
</configuration>

Be aware that this not an officially supported way of using PowerShell, so it might break other stuff ...