Set Database Owner using Powershell

 

Quick script to set the database owner using powershell.  Sure, you could do this in t-sql by just using EXEC sp_changedbowner, but where’s the fun in that?  Also, you can do multiple databases with this one.  Take that T-SQL!

image

 

$SQLAdminUser = 'AdminUser'
$SQLAdminPwd = get-content "PathToSecuredCredentials.txt" | convertto-securestring 

$srvConn = New-Object('Microsoft.SqlServer.Management.Common.ServerConnection') ('ServerName', $SQLAdminUser, $SQLAdminPwd)
$srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $srvConn

$srv.Databases | where{$_.Name -eq 'DatabaseName'} | 
foreach {
	$_.SetOwner('sa')
	$_.Alter();
}

			

Use at your own risk.