Dropping a database
This recipe shows how you can drop a database, using PowerShell and SMO.
Getting ready
This task assumes you have created a database called TestDB
. If you haven't, create one by following the steps in the Creating a database recipe.
How to do it...
The following are the
steps to drop your TestDB
database:
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
Import the
SQLPS
module, and create a new SMO Server object:#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run it:
$dbName = "TestDB" #need to check if database exists, and if it does, drop it $db = $server.Databases[$dbName] if ($db) { #we will use KillDatabase instead of Drop #Kill database will drop active connections before #dropping...