Remove Sql Login using Powershell

Quick script to remove a login from sql server using powershell.  This will iterate through the databases and the users in said databases to remove the users from them before dropping the login itself.  This uses sqlpsx.  Use at your own risk.

Import-Module SqlServer
$srv = "ServerInstance"
$loginName = "LoginName"

$login = Get-SqlLogin -sqlserver $srv | where{$_.Name -eq $loginName}
if($login -eq $null)
{
	return;
}

$dbs = Get-SqlDatabase -sqlserver $srv -force
foreach($db in $dbs)
{
	$logins = $db.EnumLoginMappings();
	foreach($dbLogin in $logins)
	{	
		#Write-Host $dbLogin.LoginName
		if($dbLogin.LoginName -eq $loginName)
		{
			Remove-SqlUser -dbname $db.Name -sqlserver $srv -name $dbLogin.LoginName
		}
	}
}
Remove-SqlLogin -sqlserver $srv -name $loginName
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: