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?
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!
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.
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).
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
I found a different command to do this. It was simply:
invoke-sqlcmd -ServerInstance ".\SC" -U "sa" -P "MyPlainTextPass" -Query "Drop database MyDatabase;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With