title: How to drop sql server database that has not been logged in for over 30 days
body: <p>I have 3 SQL Server instances running on 3 different servers. I want to be able to automatically drop any database that has not been logged in for more than 30 days.I am trying to do this in power-shell see below code:</p>
  
  <pre><code>$SQLInstances = "sql2016", "sql2014", "sql2012"
  
  $SQLQuery = "SELECT * FROM sys.databases  WHERE name not in  ('tempdb','model', 'msdb', 'master','EVN') and name not like '%report%'"
  
  foreach($sqLInstance in $SQLInstances) {
  
      $ListOfDatabases = Invoke-Sqlcmd -ServerInstance $sqLInstance -Database "master" -Query $SQLQuery
  
      ForEach ($Database in $ListOfDatabases ) {
  
      Invoke-Sqlcmd -ServerInstance $sqLInstance -Database "$Database" -Query "IF (SELECT * FROM sys.dm_exec_sessions WHERE DATEDIFF(day, LOGIN_TIME , GETDATE()) &gt; 30 ) 
  
          BEGIN
  
          DROP DATABASE $Database
  
          END "
  
      }
  
  
  }
  </code></pre>
  
  <p>I'm getting stuck on how to drop the databases. The last thing I would need is to send an email with a list of databases that will be/have been dropped.</p>
  
  <p>Any suggestions on how my code should be like?</p>