Drop Users & Logins from Sql Server with Powershell

With our trust being severed, we now have a bunch of windows logins that need to be removed from the untrusted domain.  This script will iterate through all the databases and drop all the users specified in the array, then drop the login from the server.  Use at your own risk!

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$Error.Clear()
cls

$servers = Get-Content c:\Test\Servers.txt
$logins = @("aaLogin","TestLogin")

foreach($server in $servers)
{
	$srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $server
	
	#drop database users
	foreach($database in $srv.Databases)
	{
		foreach($login in $logins)
		{
			if($database.Users.Contains($login))
			{
				$database.Users[$login].Drop();
			}
		}
	}
	
	#drop server logins
	foreach($login in $logins)
	{
		if ($srv.Logins.Contains($login)) 
		{ 
			$srv.Logins[$login].Drop(); 
		}
	}
}


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.