title: How to reliably overwrite existing database using Powershell Restore-SqlDatabase cmdlet
body: <p>I got this cmdlet to restore a database and it works fine if there is nothing using the existing database.  </p>
  
  <pre><code>Restore-SqlDatabase -ServerInstance $databaseServerInstance -Database $database -BackupFile $backupLocation -ReplaceDatabase
  </code></pre>
  
  <p>But overwrite fails when the database is in use with:</p>
  
  <blockquote>
    <p>System.Data.SqlClient.SqlError: Exclusive access could not be obtained
    because the database is in use</p>
  </blockquote>
  
  <p>I couldn't figure out if there is an easy way (via an argument) to override this and kill connections or put the database in single user mode.  is there such a thing?  or do I have to switch to SMO to do anything more complicated than a basic restore?</p>
  
  <p>I am now using a workaround of using SMO API to drop the DB first but would love to simplify this if its possible.</p>
  
  <pre><code>$srv = new-object Microsoft.SqlServer.Management.Smo.Server($databaseServerInstance)
  
  # If the database exists then drop it otherwise Restore-SqlDatabase may fail if connections are open to it
  if ($srv.Databases[$database] -ne $null)
  {
      $srv.KillAllProcesses($database)
      $srv.KillDatabase($database)
  }
  
  
  Restore-SqlDatabase -ServerInstance $databaseServerInstance -Database $database -BackupFile $backupLocation -ReplaceDatabase
  </code></pre>