I did something that could be related. I enter one domain and try to get a list of directories of a shared folder in another domain. For this, I use LogonUser and Impersonate. The code is as follows (sorry, I do not have a SQL server to try your exact script) ...
public class Login : IDisposable { public Login(string userName, string domainName) { _userName = userName; _domainName = domainName; } string _userName = null; string _domainName = null; IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); WindowsImpersonationContext impersonatedUser = null; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; [DllImport("advapi32.dll", SetLastError = true, EntryPoint = "LogonUser")] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", SetLastError = true, EntryPoint = "LogonUser")] public static extern bool LogonUserPrompt(String lpszUsername, String lpszDomain, IntPtr lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); public void AccessShare(string password) { tokenHandle = IntPtr.Zero; bool returnValue = LogonUser(_userName, _domainName, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); }
I used this with Directory.GetDirectories (UNCPath), where the path leads to a machine in another domain, and it works there. I have not tried it to implement "runas" yet.
I call it that ...
using(var login = new Login("myname","mydomain)) { login.AccessShare("mypassword"); // do stuff }
Perhaps you can adapt it to your problem. LMK
source share