Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop SQL Server database from powershell

I have a SQL Server instance on my local computer called .\SC. I want to drop a database from that instance using a PowerShell script. I need to login with the sa user for my database.

This is the code I have so far, but it doesn't work:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$srv = new-object Microsoft.SqlServer.Management.Smo.Server(".\SC")
$conContext = $srv.ConnectionContext
$conContext.LoginSecure = $FALSE
$conContext.Login = "sa"
$conContext.Password = "MyPlainTextPass"
$srv2 = new-object Microsoft.SqlServer.Management.Smo.Server($conContext)
$srv2.Databases

That last line is supposed to list the databases in my SQL instance... but it gives me this error:

The following exception occurred while trying to enumerate the collection: "Failed to connect to server .\SC.". At line:1 char:1 + $srv2.Databases + ~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException + FullyQualifiedErrorId : ExceptionInGetEnumerator

What am I doing wrong?

like image 952
user952342 Avatar asked Jun 10 '14 19:06

user952342


People also ask

How do I drop a specific database?

Syntax. DROP DATABASE databasename; Note: Be careful before dropping a database. Deleting a database will result in loss of complete information stored in the database!

How do I disconnect a SQL Server database?

In SQL Server Management Studio Object Explorer, connect to the instance of the SQL Server Database Engine and then expand the instance. Expand Databases, and select the name of the user database you want to detach. Right-click the database name, point to Tasks, and then select Detach.

How do I disconnect a database in Visual Studio?

You'll find SSOE under the View menu. Once you have connected to your database server you can delete a database by right-clicking on it and selecting Delete (or selecting it and hitting the Del key).


2 Answers

The only way to make it work for me was to force any other connections to the database to close, through the following command:

Invoke-SqlCmd -ServerInstance $Server @Auth `
    -Query "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name ='MyDBName') `
                BEGIN `
                    ALTER DATABASE [MyDBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; `
                    DROP DATABASE [MyDBName]; `
                END;" `
    -Verbose

The backticks (`) are necessary, otherwise this command would have to be inlined

like image 180
ccoutinho Avatar answered Oct 21 '22 03:10

ccoutinho


I found a different command to do this. It was simply:

invoke-sqlcmd -ServerInstance ".\SC" -U "sa" -P "MyPlainTextPass" -Query "Drop database MyDatabase;"
like image 21
user952342 Avatar answered Oct 21 '22 01:10

user952342