How to terminate sqlps session and close database connection after running Invoke-Sqlcmd?

时间:2018-10-02 09:11:45

标签: sql-server powershell sqlps

I have the following Powershell script which uses the Invoke-Sqlcmd commandlet to execute SQL queries:

Push-Location
Invoke-Sqlcmd -ServerInstance "localhost\SQLEXPRESS" -Query "DROP DATABASE DBB;"
Invoke-Sqlcmd -ServerInstance "localhost\SQLEXPRESS" -Query "CREATE DATABASE DBB;"
Invoke-Sqlcmd -ServerInstance "localhost\SQLEXPRESS" -Database "DBB" -InputFile "AllTables.sql"
Pop-Location

I cannot run this script multiple times because the first run does not properly close its database connection.

On the second run when dropping the DBB database a "Database already in use" Error occurs.

How to properly exit the sqlps session and close the database connection? So far I get around this issue by restaring the SqlServer instance which is pretty lame.

0 个答案:

没有答案