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

后端 未结 4 2034
猫巷女王i
猫巷女王i 2021-02-20 11:39

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

PS C:\\> Get-Command sqlcmd.exe

Definition
----------
C:\\Program Files\\Microsof         


        
4条回答
  •  太阳男子
    2021-02-20 11:58

    This is code that works for me under adverse conditions (see my comments just after the code). I suspect that simpler code may work in a more common environment, but I haven't dug into it.

    The instance pipe times out after a few minutes. You're better off if you can connect using (localdb)\instanceName, because those connections don't seem to time out.

    function Get-InstancePipeName ([string] $localDbName)
    {
      while (!($pipeName = ((sqllocaldb info $localDbName) -match 'instance pipe name').Split(':', 2)[1].Trim()))
      {
        sqllocaldb start $localDbName | Out-Null
      }
      return $pipeName
    }
    
    $scsb   = New-Object System.Data.SqlClient.SqlConnectionStringBuilder
    $scsb.psbase.DataSource = Get-InstancePipeName localDbName # <== put your db name here
    $sc     = New-Object System.Data.SqlClient.SqlConnection $scsb.ConnectionString
    
    $smoSc  = New-Object Microsoft.SqlServer.Management.Common.ServerConnection $sc
    $smoSvr = New-Object Microsoft.SqlServer.Management.Smo.Server $smoSc
    Invoke-Sqlcmd -ServerInstance $smoSvr -Query 'select 1'
    

    For reasons currently outside my control, the execution environment where this runs is unusual. It's a remote execution environment with an incomplete session context. Also, I had to redefine USERPROFILE to work around some other issues.

    [later edit: I recently found a way to extend the timeout - I had to add a RECONFIGURE after the 2nd sp_configure and (as recommended) stop and start the localdb to get it to take effect)]

提交回复
热议问题