Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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 don't have it, create the database TestDB by following the steps in the Creating a database recipe.

How to do it...

Here are the steps to drop your TestDB database:

  1. Open PowerShell ISE as administrator.

  2. 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 = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run:

    $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 the database
          $server.KillDatabase($dbName)
    }

How it works...