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.