dbatools is a free PowerShell module with over 180 SQL Server administration, best practice and migration commands included.


Set-DbaDatabaseOwner

This function will alter database ownership to match a specified login if their current owner does not match the target login. By default, the target login will be ‘sa’ (or renamed sa account), but the function will allow the user to specify a different login for ownership. The user can also apply this to all databases or only to a select list of databases, which are autopopulated from the SQL Server.

Screenshot

Set-DbaDatabaseOwner

Examples

To set the database owner to ‘sa’ on all databases where the owner does not match ‘sa’.

Set-DbaDatabaseOwner -SqlServer localhost

To set the database owner to DOMAIN\account on all databases where the owner does not match DOMAIN\account. Note that TargetLogin must be a valid security principal that exists on the target server.

Set-DbaDatabaseOwner -SqlServer localhost -TargetLogin DOMAIN\account

To set the database owner to ‘sa’ on the db1 and db2 databases if their current owner does not match ‘sa’

Set-DbaDatabaseOwner -SqlServer sqlserver -Databases db1, db2

References

Dan Guzman’s Database Owner Troubles.

Author

This command was created by Mike Fal. You can find Mike on Twitter, mikefal.net and LinkedIn.

Get-Help

From PowerShell, execute Get-Help Set-DbaDatabaseOwner -Detailed for more information on this function.

Source Code

Want to see the source code? View Set-DbaDatabaseOwner.ps1 on GitHub
 

Related commands