Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Invoke-sqlcmd keeping connection open and trying to reuse it

I have a Powershell script that uses invoke-sqlcmd to apply scripts to a series of development databases. I loop through a list of scripts and compare it to the current release level of the database and then apply the required scripts to get the DB to the release level it needs to be at. Certain databases are reference databases and are in a READ_ONLY state. I connect to those database run an alter DB script setting them to READ_WRITE apply the script then change the back to READ_ONLY. Overall the script works well, the issue is it looks like when PowerShell first opens a connection to the database and applies the first script and then goes to alter the DB back to READ_ONLY the database has objects locked. I've traced it back to the previous connection and a Shared_Transaction_Workspace lock (sys.dm_tran_locks) for what looks to be the previous powershell connection. Why is this connection still open after the invoke-sqlcmd has completed and is there anything I can do about it? Can I force invoke-sqlcmd to use a new connection for each invocation of the cmdlet?

I have tried a messy fix killing the offending connection and then retrying the connection but I think there is something better.

like image 445
Steve Fibich Avatar asked Dec 19 '12 14:12

Steve Fibich


People also ask

What does invoke-Sqlcmd do?

The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.

How do I connect to a PowerShell script using SQL Server?

Use Win + R , on your Windows computer, and type PowerShell to launch a new Windows PowerShell session. SQL Server provides a PowerShell module named SqlServer. You can use the SqlServer module to import the SQL Server components (SQL Server provider and cmdlets) into a PowerShell environment or script.


1 Answers

I've always done this and it seems to work:

[System.Data.SqlClient.SqlConnection]::ClearAllPools()
like image 82
Paul Heller Avatar answered Nov 09 '22 18:11

Paul Heller