Search code examples
powershellinvoke-sqlcmd

Dropping Database in Powershell with Invoke-Sqlcmd tells me DB is in use even though it's not


I am trying to drop a database like this

Invoke-Sqlcmd -Database Dbname-ServerInstance ".\SQLEXPRESS" -Query "drop database DbName;"

in a powershell script and I get this message:

Invoke-Sqlcmd : Cannot drop database "DbName" because it is currently in use.
At line:1 char:1
+ Invoke-Sqlcmd -Database Dbname-ServerInstance ".\SQLEXPRESS" -Que ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
+ FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

The Database is not in use. What am I doing wrong?


Solution

  • The database is in use -- you're connected to it! Try -Database master. – Jeroen Mostert