I have a function that connect to a remote computer using WMI. When I launch it with administrator privileges, the system says RPC server error.
I have the same kind of script in Powershell, it works correctly, no RPC server error (so WMI is working on the network, firewall isn't blocking it. I only found that kind of answer on the internet), and other softwares written in c# in the company are working correctly with those computers (the developer is no longer working for the company and I can't get my hand on the source code )
The same issue occurs whether I use the name of the computer or its IP adress.
static public string GetUsername(string computer)
{
string username = string.Empty;
ManagementScope scope = new ManagementScope("\\\\computer\\root\\cimv2");
//scope.Connect(); If I activate this line, the error occurs on this line
string queryString = "select LogonId from win32_logonsession where logontype = 2";
ManagementObjectSearcher query = new ManagementObjectSearcher(scope, new SelectQuery(queryString));
foreach (ManagementObject mo in query.Get()) //if scope.connect(); is not activated, it's blocking on this line
{
username = mo["LogonId"].ToString();
}
return username;
}
I tried to run my software from the Visual Studio or directly from the .exe (using administrator). I also tried an impersonation as a workstation admin programatically, but the problem is still there.
Thank you in advance for your kind help.
EDIT :
I already tried the solution with connectionOptions like this :
options.Username = "YOUR USERNAME";
options.Password = "YOUR PASSWORD";
options.Authority = "ntlmdomain:YOURDOMAIN";
and like this :
options.Username = "YOUR USERNAME";
options.Password = "YOUR PASSWORD";
options.Authority = "Kerberos:YOURDOMAIN";
and added the impersionation options
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
Still not working.
Have you tried setting a username and password for the managmentscope like this?
static public string GetUsername(string computer)
{
string username = string.Empty;
ConnectionOptions options = new ConnectionOptions();
options.Username = "YOUR USERNAME";
options.Password = "YOUR PASSWORD";
options.Authority = "ntlmdomain:YOURDOMAIN";
ManagementScope scope = new ManagementScope("\\\\computer\\root\\cimv2",options);
//scope.Connect(); If I activate this line, the error occurs on this line
string queryString = "select LogonId from win32_logonsession where logontype = 2";
ManagementObjectSearcher query = new ManagementObjectSearcher(scope, new SelectQuery(queryString));
foreach (ManagementObject mo in query.Get()) //if scope.connect(); is not activated, it's blocking on this line
{
username = mo["LogonId"].ToString();
}
return username;
}
For more information have a look at the MSDN page for ManagementScope here And for the ConnectionOptions here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With