SMO Impersonate Windows Account

I received an email from a colleague this morning asking how to use SMO to impersonate another windows user to connect to SQL Server. Below is how this can be achieved using SMO:

Dim myServerConn As New Microsoft.SqlServer.Management.Common.ServerConnection

myServerConn.LoginSecure = True

myServerConn.ConnectAsUser = True

myServerConn.ConnectAsUserName = “username@domain”

myServerConn.ConnectAsUserPassword = “password*”

myServerConn.ServerInstance = “ServerInstance”

myServerConn.Connect()

The one thing to be aware of is that the username needs to be in the format username@domain instead of username\domain.