C# WMI Error Message "Not Supported" - c#

I'm trying to install/add a networked printer on a remote computer using WMI. The below code works perfectly when i enter my local computer name but i get an error message "Not Supported" when i use any remote computer name. I looked up the WMI Error on MSDN and read "Feature or operation is not supported." But also noticed on MSDN they have a 'howto' add a new printer connection to a remote computer and there VBs example. I copied the VBs example and ran it and also recieved the same error "Not Supported". What am i missing? Any idea on what I'm doing wrong?
ConnectionOptions conOp = new ConnectionOptions();
conOp.Impersonation = ImpersonationLevel.Impersonate;
conOp.Authentication = AuthenticationLevel.Default;
conOp.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(#"\\pcname\ROOT\CIMV2", conOp);
manScope.Connect();
ManagementClass manClass = new ManagementClass(manScope, new ManagementPath("Win32_Printer"), null);
ManagementBaseObject inParams = manClass.GetMethodParameters("AddPrinterConnection");
inParams["Name"] = #"\\server\printer";
////////Error Occurs Here
ManagementBaseObject outParams = manClass.InvokeMethod("AddPrinterConnection", inParams, null);

Related

unable to get installed software details of vm machine of azure using System.Management

My requirement is to get installed software details of vm machine of azure and store the details in db. but when I try to get the details using System.Management class I am getting the below error
System.Runtime.InteropServices.COMException: 'The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)'
below is my sample code I am using to get the software details
string SoftwareQuery = "SELECT * FROM Win32_Product";
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "bla bla";
connection.Password = "Password";
connection.EnablePrivileges = true;
connection.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope managementScope = new ManagementScope(#"\\xxxx.xxxx.cloudapp.azure.com:3389\root\CIMV2", connection);
managementScope.Path = ManagementPath.DefaultPath;
managementScope.Connect();
ObjectQuery queryObj = new ObjectQuery(SoftwareQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, queryObj);
foreach (ManagementBaseObject managementObj in searcher.Get())
{
//get the software list here
}
Note: The above code is working on intranet properly
Please let me know anyone have solution on this.
It might be related to the Windows Management Instrumentation service being in a stopped state. Take a look at Starting and Stopping the WMI Service.
Hope it helps!

WMI remote process fails to start, starts locally fine

The following code works when "SelectedMachine" is the localhost where the C# exe is being launched from. When "SelectedMachine" is a remote machine, the process simply doesn't launch. No exceptions, no errors, acts as if it's successful, however, the process never starts. Any ideas?
object[] processToRun = { "notepad.exe" };
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(#"\\{0}\ROOT\CIMV2", SelectedMachine), connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
processClass.InvokeMethod("Create", processToRun );
Edit: When I go through wbemtest, same behavior occurs. When the Namespace is root\cimv2 (local), the process executes, when it is \RemoteMachineName\root\cimv2, it claims success but never starts on the remote machine. Not sure what I'm missing here.
This behavior is described in the Win32_Process.Create method documentation.
For security reasons the Win32_Process.Create method cannot be used to
start an interactive process remotely.

Remote running msiexec on Win32_Process

The main task of this short part is get some computer name and install on this PC needed software (throught msiexec.exe)
I do this
{
Credential creds = new Credential();
UserAttr UserCredential = new UserAttr();
UserCredential = creds.DefaultFlagsTest();
ConnectionOptions connection = new ConnectionOptions();
connection.Username = UserCredential.UserName;
connection.Password = UserCredential.password;
connection.Authentication = AuthenticationLevel.PacketPrivacy;
connection.Authority = "ntlmdomain:tcc1";
ManagementScope scope = new ManagementScope(
"\\\\"+computerName+"\\root\\CIMV2", connection);
scope.Connect();
ManagementClass classInstance =
new ManagementClass(scope,
new ManagementPath("Win32_Process"), null);
ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");
inParams["CommandLine"] = #"msiexec.exe /qb /m log.mif /i ""\\tcc1-pgh10.tcc1.local\swshare$\Packages\NetAgent_10.0.3361\exec\Kaspersky Network Agent.msi""";
ManagementBaseObject outParams = classInstance.InvokeMethod("Create", inParams, null);
int res = int.Parse(outParams["ReturnValue"].ToString());
if (res == 0)
{
MessageBox.Show(outParams["ReturnValue"].ToString(), "Result");
}
else throw new System.ComponentModel.Win32Exception(res);
Close();
}
the program returns 0, but its doesnt mean that msiexec is complete with the same success. Error is check path of package .. or smth. But what i see in a log file log.mif:
..............................
START ATTRIBUTE
NAME = "Product"
ID = 2
ACCESS = READ-ONLY
STORAGE = SPECIFIC
TYPE = STRING(64)
VALUE = "\tcc1-pgh10.tcc1.local\swshare$\Packages\NetAgent_10.0.3361\exe"
END ATTRIBUTE
..............................
he crops the name of package at 64 symb. The reason is that parametr CommandLine of Win32_Process.Create has this limit.
I don't know how to overcome this...
Win32_Process.Create also has property CurrentDirectory, thath seems can solve this propblem. But he can't process UNC paths.
and i can't do the install directory shorter. it is not right. (And i can say that i've done this. And its worked)
Please, maybe you know how to solve this propblem with a long installation path?
different properties as TARGETDIR or INSTALLDIR set only path TO install, no FROM...
I gave up
START ATTRIBUTE
NAME = "Product"
ID = 2
ACCESS = READ-ONLY
STORAGE = SPECIFIC
TYPE = STRING(64)
VALUE = "\tcc1-pgh10.tcc1.local\swshare$\Packages\NetAgent_10.0.3361\exe"
END ATTRIBUTE
The value is limited to 64symb including path. It will be working properly only on a local machine without using UNC paths

WMI Namespace "Not Found"

I'm trying to run a bat file remotely (from XP to 2003) and running into a problem connecting to any WMI namespace other than cimv2. The code below hits a "Not Found" exception in the "GetMethodParameters" call. But if I replace "directory" with "cimv2", everything is gravy.
ConnectionOptions theConnection = new ConnectionOptions();
theConnection.Username = conDet.User;
theConnection.Password = conDet.Pwd;
theConnection.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope theScope = new ManagementScope(String.Format(#"\\{0}\root\directory", conDet.Server), theConnection);
theScope.Connect();
ManagementClass processClass = new ManagementClass(theScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
enter code here
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = filename;
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
I've checked the security on my machine and the server and the two namespaces have identical security settings. Any ideas what's going on?
Thanks.
you are using a wrong namespace, the Win32_Process WMI class is defined in root\cimv2.
So you must rewrite your code to
ManagementScope theScope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", conDet.Server), theConnection);

Creating share programmatically fails with error 9

ObjectGetOptions options = new ObjectGetOptions();
ManagementPath p = new ManagementPath("\\\\server01\\root" + "\\cimv2:Win32_Share");
// Make a connection to a remote computer.
ManagementScope scope = new ManagementScope("\\\\server01\\root\\cimv2");
scope.Connect();
// Create a ManagementClass object
ManagementClass managementClass = new ManagementClass(scope, p, options);
// Create ManagementBaseObjects for in and out parameters
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
// Set the input parameters
//inParams["Description"] = String.Empty;
inParams["Name"] = "test";
inParams["Path"] = #folderPath;
inParams["Type"] = 0x0; // Disk Drive
// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to share directory. Error code: " + outParams.Properties["ReturnValue"].Value);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
I am using the following code to set up a share, but I am always getting a return value of 9 which means invalid name. I am passing a string and have tried to use an explicit string and I still get error 9.
I am creating the share remotely rather than on local machine however. I have tried to make sure I am connecting to the remote WMI provider, but I am not sure if I have been successful.
Any suggestions from WMI gurus and others is greatly appreciated.
Found the answer on another site. The folder path needs to be the local path to the machine the share is created on, not a UNC path like I was using.
I had the same error. In my case though the problem was a trailing backslash. Doing directoryPath.TrimEnd('\') solved the problem.
Return Values
Returns one of the values in the following table or any other value to indicate an error.
0 – Success
2 – Access denied
8 – Unknown failure
9 – Invalid name
10 – Invalid level
21 – Invalid parameter
22 – Duplicate share
23 – Redirected path
24 – Unknown device or directory
25 – Net name not found

Categories

Resources