WMI connection error C# - c#

using System;
using System.Management;
public class Class1
{
public static void Main()
{
string strComputer = string.Format(#"machineName.domainname\root\cimv2");
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Packet;
options.Authority = "ntlmdomain:InsTIL.com:InsTIL.com";
options.Username = "usr";
options.Password = "pwd";
ManagementScope oMs = new ManagementScope(strComputer, options);
SelectQuery query =new SelectQuery("Select * From Win32_Directory Where Name ='"+string.Format(#"C:\Scripts")+"'");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,query);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
if (oReturnCollection.Count < 1)
{
Console.WriteLine("Folder does not exist");
}
else
{
Console.WriteLine("Folder does exist");
}
}
}
I'm trying to connect to remote machine and checking existence of folder.But I'm getting below mentioned error.
I tried and incorporated changes discussed in remote wmi connection c# - invalid parameter error
Program abruptly stops working and throws below error:
Unhandled Exception: System.Management.ManagementException: Invalid parameter
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStat
us errorCode)
at System.Management.ManagementPath.CreateWbemPath(String path)
at System.Management.ManagementPath..ctor(String path)
at Class1.Main()

You need backslashes before your machine name. Change this:
string strComputer = string.Format(#"machineName.domainname\root\cimv2");
to this:
string strComputer = string.Format(#"\\machineName.domainname\root\cimv2");

Related

How can I read the CPU Load of a remote PC with CIM session instead of WMI? I have to use the admin credentials of the remote PC

I am using the following code for reading CPU Load on remote PC with Win XP. I have to use the credentials on the remote PC. It is working fine. But how can I use CIM session instead of WMI?
public void Read_CPU_Load_WMI()
{
WMI_path = "\\\\" + TagService.IP_to_Connect + "\\root\\cimv2";
System.Management.ConnectionOptions options = new System.Management.ConnectionOptions();
options.Username = username;
options.Password = password;
ManagementScope scope = new ManagementScope(WMI_path, options);
scope.Connect();
SelectQuery query = new SelectQuery("select PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor where Name='_Total'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
CPU_Load_WMI_int = Convert.ToInt16(queryObj["PercentProcessorTime"]);
CPU_Load_WMI_str = queryObj["PercentProcessorTime"].ToString();
}
}
I have started as following but cannot finish it
public void Read_CPU_Load_CIM
{
WMI_path = "\\\\" + TagService.IP_to_Connect + "\\root\\cimv2";
System.Management.ConnectionOptions options = new System.Management.ConnectionOptions();
options.Username = username;
options.Password = password;
string Namespace = #"root\cimv2";
string OSQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor where Name='_Total'";
CimSession mySession = CimSession.Create(WMI_path);
IEnumerable<CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);
//CPU_Load_WMI_int = ???
}

restart a service in c#

When I try to execute the below code, I get the error - RPC server is unavailable.
string username = "****";
string password = "****";
server = comboBox1.SelectedItem.ToString();
service = "****";
ServiceController windowsservice = new ServiceController(service, server);
try
{
ConnectionOptions connectopt = new ConnectionOptions();
connectopt.Username = username;
connectopt.Password = password;
connectopt.EnablePrivileges = true;
connectopt.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(#"\\'"+server+"'\\root\\cimv2", connectopt);
scope.Connect();
}
But when I hardcode the value of server name in the line
ManagementScope scope = new ManagementScope(#"\\'"+server+"'\\root\\cimv2", connectopt);
it works fine with no errors
Any help would be much appreciated

Error Connecting to a VM on a different domain

This code works fine when opening two other VMs but gives me an RPC error on
opening a computer on a different domain. At the moment I am using the ConnectionOptions class to connect to the remote computer
`options.Username = dif_users[i]; // Assume correct user name
options.Password = dif_passwords[i]; // Assume correct password
if (i == 2) // To execute for the third VM. (i = 0 in the beginning)
{
//
options.Authentication = AuthenticationLevel.Packet;
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "ntlmdomain:DIFFERENT_DOMAIN";
}
ManagementScope scope = new ManagementScope("\\\\" + comps + "\\root\\cimv2", options);
scope.Connect(); // RPC server is unavaialaible
`

Get hardware information of Windows Server

Currently I'm using following methods to get hardware information (network adapter, processor, hdd)
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_processor");
ManagementObject dsk = new ManagementObject(#"win32_logicaldisk.deviceid=""c:""");
My app is desktop, client-server (app and db are installed on server).
This methods get information for client. Is there a way to get hardware information for some node on lan - I want to get hardware information for server?
This is a subroutine I use in order to query remote hosts (here I assume I already configured WMI on the remote computer):
public string getWMI(string[] parameters)
{
string ip = parameters[0];
string username = parameters[1];
string password = parameters[2];
string query = parameters[3];
string result = "";
ConnectionOptions options = new ConnectionOptions();
ManagementScope scope;
options.Username = username;
options.Password = password;
try
{
scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);
scope.Connect();
if (scope.IsConnected)
{
ObjectQuery q = new ObjectQuery(query);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, q);
ManagementObjectCollection objCol = searcher.Get();
foreach (ManagementObject mgtObject in objCol)
{
result = result + mgtObject.GetText(TextFormat.CimDtd20);
}
}
else
{
}
}
catch (Exception e)
{
writeLogFile("WMI Error: " + e.Message);
writeLog("WMI Error: " + e.Message);
}
return result;
}
In that subroutine I use a direct query such as "select * from Win32_ComputerSystem" but you can use ManagementClass as well.
I want to get hardware information for server?
WMI can poin to another server as long as:
The eserver exposes WMI
The fireawall does not block it.
Your user account has the rights on the other server.
Simple like that.

Is a process running on a remote machine?

I have three remote PC's to which I remotely connect. I am trying to write a simple Windows application that would display in a single window whether a particular process is running on either of the machines, e.g.
Server1: Chrome not running
Server2: Chrome IS running
Server3: Chrome IS running
I used WMI and C#. So far I've got this much:
ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = #"domain\username";
connectoptions.Password = "password";
//IP Address of the remote machine
string ipAddress = "192.168.0.217";
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2");
scope.Options = connectoptions;
//Define the WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_Process");
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject process in collection)
{
// dwarfs stole the code!! :'(
}
}
I think it is all set up correctly, but if I MessageBox.Show(process.ToString()) inside the foreach loop, I get a whole bunch of message boxes with the following text:
\\username\root\cimv2:W32_Process.Handle="XXX"
I am kind of stuck. Is there any way I can "translate" that XXX to a process name? Or else, how can actually get the names of the processes so I can use an if statement to check whether it is a "chrome" process?
Or...is my implementation an overkill? Is there an easier way to accomplish this?
Thanks a lot!
In your foreach, try this:
Console.WriteLine(process["Name"]);
You can filter the name of the process to watch in the WQL sentence, so you can write something like this
SelectQuery query = new SelectQuery("select * from Win32_Process Where Name='Chrome.exe'");
Try this sample app
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Process Where Name='Chrome.exe'");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
//for each instance found, do something
Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
Try Process.GetProcesses("chrome", "computerName");
Defined in System.Diagnostics.Process as
public static Process[] GetProcessesByName(
string processName,
string machineName)

Categories