Lenovo BIOS WMI - InvalidQuery - c#

I'm about to create a tool which gets some system information.
Only the Lenovo BIOS (WakeOnLAN) request isn't doing what I want.
The debugger always stops with a "invalid request" error message.
I tried the following...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi", "SELECT * FROM Lenovo_BiosSetting WHERE InstanceName='ACPI\\PNP0C14\\1_0'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting.InstanceName='ACPI\\PNP0C14\\1_0'");
Code:
//LenovoWOL
public string GetLenovoWOL()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting", "SELECT * FROM ACPI\\PNP0C14\\1_0");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return Environment.NewLine + wmi.GetPropertyValue("CurrentSetting").ToString();
}
catch { }
}
return "Unknown";
}
Only if I remove the InstanceName part, the code works.
Could someone if you tell me, what I'm doing wrong.
Thanks for your help
Adrian

I found a solution.
Here my code. It's not pretty but it works.
ManagementPath path = new ManagementPath()
{
NamespacePath = #"root\wmi",
Server = textBox1.Text
};
ManagementScope scope = new ManagementScope(path);
SelectQuery Sq = new SelectQuery("Lenovo_BiosSetting");
ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher(scope, Sq);
ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
foreach (ManagementObject MO in osDetailsCollection)
{
if (MO["CurrentSetting"].ToString().Contains("WakeOnLAN"))
{
string[] arr = new string[3];
ListViewItem itm;
//add items to ListView
arr[0] = "";
arr[1] = "WakeOnLAN";
arr[2] = MO["CurrentSetting"].ToString();
itm = new ListViewItem(arr);
listView200.Items.Add(itm);
}
}
Adrian

Related

how to format drive with 32KB cluster

I am not a C# programer but I need to format drive with 32KB cluster using C#. I found "Format method of the Win32_Volume class" but when I am trying to format drive I always get an error 15 (Cluster size is too small). This is my code:
public static int DriveFormatting(string driveLetter)
{
string FileSystem = "FAT32", Label = "";
Boolean QuickFormat = true, EnableCompression = false;
UInt32 ClusterSize = 32;
int result = -1;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume WHERE DriveLetter = '"+ driveLetter +"'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject management in searcher.Get())
{
Console.WriteLine("Formating disk " + driveLetter + "...");
result = Convert.ToInt32(management.InvokeMethod("Format", new object[] { FileSystem, QuickFormat, ClusterSize, Label, EnableCompression }));
}
return result;
}
How can I do this? Thanks in advance.

ManagementObjectSearcher Get() method returns no results

I'm trying to terminate a process on a remote machine with WMI / C# on .NET 4.5. In the code below, when the Get method is called on the ManagementObjectSearcher instance nothing is returned, so the line inside the foreach is not reached. The ManagementScope is connected and the query variable contains the name of the process for termination.
Thx for any help.
try
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(#"\\{0}\ROOT\CIMV2", NetworkName), connOptions);
manScope.Connect();
var query = new SelectQuery("select * from Win32_process where name = '" + ProcessName + "'");
using (var searcher = new ManagementObjectSearcher(manScope, query))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
}
}
}
catch (ManagementException err)
{
//Do something with error message here
}
As outlined in my comment above, for completeness here's the code with my changes that are as follows.
try
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(#"\\{0}\ROOT\CIMV2", NetworkName), connOptions);
manScope.Connect();
ProcessName = ProcessName + ".exe";
using (var searcher = new ManagementObjectSearcher(manScope, new SelectQuery("select * from Win32_Process where Name = '" + ProcessName + "'")))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
}
}
}
catch (ManagementException err)
{
//Do something with error message here
}
In my case i was unable to receive CPU utilization value remotely using WMI query:
SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name='_Total'
I changed project build platform target from Any CPU to x64 to match my system bitness, and problem was solved. Another way is uncheck Prefer 32-bit checkbox when Any CPU is selected.
Use the Count property to check, whether it contains any record. That is, if(searcher.Get().count == 0) returns true, means no record is present.

I'm using WMI in C# to get all the installed softwares but it doesn't show all the softwares only Microsoft ones

public ManagementScope GetScope()
{
try
{
//string classScope="winmgmts:" + "{impersonationLevel=impersonate}!\\" + strComputer + "\\root\\cimv2";
string serverString = #"root\cimv2";
ManagementScope scope = new ManagementScope(serverString);
ConnectionOptions options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
Authentication = AuthenticationLevel.Connect,
EnablePrivileges = true
};
scope.Options = options;
return scope;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
public void InvokeMethodsFunctions1()
{
ManagementScope mScope = GetScope();
mScope.Connect();
if (mScope.IsConnected)
{
ManagementClass processClass =
new ManagementClass(mScope.Path);
ManagementObjectSearcher mos = new ManagementObjectSearcher(mScope, new ObjectQuery("SELECT * FROM Win32_Product"));
//get collection of WMI objects
ManagementObjectCollection queryCollection = mos.Get();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"Result.txt"))
{
textBox1.Text = "";
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
string line = " " + m["Name"] + " , InstallDate : " + m["InstallDate"] + " LocalPackage : " + m["LocalPackage"];
Console.WriteLine(line);
file.WriteLine(line);
textBox1.Text += line + "\n";
}
}
}
}
So whats wrong in my Code ?
There is nothing wrong , the Win32_Product WMI class only list the products installed by the Windows Installer (MSI).
I just tested the following, simplified version of your code and I see everything installed on my pc, even services I wrote and installed myself:
var products = new ManagementObjectSearcher(new ObjectQuery("SELECT * FROM Win32_Product"));
var result = products.Get();
foreach (var product in result)
{
Console.WriteLine(product.GetPropertyValue("Name").ToString());
}
Console.ReadLine();
It looks like you are narrowing your query by scope, which is possibly why you aren't seeing everything, try the above and see if you have more luck.

How to get the description of a running process on a remote machine?

I have tried two ways to accomplish this so far.
The first way, I used System.Diagnostics, but I get a NotSupportedException of "Feature is not supported for remote machines" on the MainModule.
foreach (Process runningProcess in Process.GetProcesses(server.Name))
{
Console.WriteLine(runningProcess.MainModule.FileVersionInfo.FileDescription);
}
The second way, I attempted using System.Management but it seems that the Description of the ManagementObject is the she same as the Name.
string scope = #"\\" + server.Name + #"\root\cimv2";
string query = "select * from Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
Console.WriteLine(obj["Name"].ToString());
Console.WriteLine(obj["Description"].ToString());
}
Would anyone happen to know of a better way to go about getting the descriptions of a running process on a remote machine?
Well I think I've got a method of doing this that will work well enough for my purposes. I'm basically getting the file path off of the ManagementObject and getting the description from the actual file.
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope(#"\\" + serverName + #"\root\cimv2", connection);
scope.Connect();
ObjectQuery query = new ObjectQuery("select * from Win32_Process");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
if (obj["ExecutablePath"] != null)
{
string processPath = obj["ExecutablePath"].ToString().Replace(":", "$");
processPath = #"\\" + serverName + #"\" + processPath;
FileVersionInfo info = FileVersionInfo.GetVersionInfo(processPath);
string processDesc = info.FileDescription;
}
}

Get a list of all UNC shared folders on a local network server

I'm trying to get a list of all shared folders available on a local intranet server.
The System.IO.Directory.GetDirectories() works fine for a path like \\myServer\myShare, however I'm getting an exception for a path like \\myServer:
Unhandled Exception: System.ArgumentException: The UNC path should be of the form \server\share.
Is there a way to get a list all shared folders for a server? Ultimately I'm looking for a method that can handle both scenarios based on a given path - returning a list of all shares for a given server and returning a list of all subdirectories for a given network shared folder.
Here's a technique that uses System.Management (add a reference to this assembly):
using (ManagementClass shares = new ManagementClass(#"\\NameOfTheRemoteComputer\root\cimv2", "Win32_Share", new ObjectGetOptions())) {
foreach (ManagementObject share in shares.GetInstances()) {
Console.WriteLine(share["Name"]);
}
}
Appropriate permissions are required.
I think this is what you are looking for http://www.codeproject.com/KB/IP/networkshares.aspx
private DataTable GetSharedFolderAccessRule()
{
DataTable DT = new DataTable();
try
{
DT.Columns.Add("ShareName");
DT.Columns.Add("Caption");
DT.Columns.Add("Path");
DT.Columns.Add("Domain");
DT.Columns.Add("User");
DT.Columns.Add("AccessMask");
DT.Columns.Add("AceType");
ManagementScope Scope = new ManagementScope(#"\\.\root\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_LogicalShareSecuritySetting");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
ManagementObjectCollection QueryCollection = Searcher.Get();
foreach (ManagementObject SharedFolder in QueryCollection)
{
{
String ShareName = (String) SharedFolder["Name"];
String Caption = (String)SharedFolder["Caption"];
String LocalPath = String.Empty;
ManagementObjectSearcher Win32Share = new ManagementObjectSearcher("SELECT Path FROM Win32_share WHERE Name = '" + ShareName + "'");
foreach (ManagementObject ShareData in Win32Share.Get())
{
LocalPath = (String) ShareData["Path"];
}
ManagementBaseObject Method = SharedFolder.InvokeMethod("GetSecurityDescriptor", null, new InvokeMethodOptions());
ManagementBaseObject Descriptor = (ManagementBaseObject)Method["Descriptor"];
ManagementBaseObject[] DACL = (ManagementBaseObject[])Descriptor["DACL"];
foreach (ManagementBaseObject ACE in DACL)
{
ManagementBaseObject Trustee = (ManagementBaseObject)ACE["Trustee"];
// Full Access = 2032127, Modify = 1245631, Read Write = 118009, Read Only = 1179817
DataRow Row = DT.NewRow();
Row["ShareName"] = ShareName;
Row["Caption"] = Caption;
Row["Path"] = LocalPath;
Row["Domain"] = (String) Trustee["Domain"];
Row["User"] = (String) Trustee["Name"];
Row["AccessMask"] = (UInt32) ACE["AccessMask"];
Row["AceType"] = (UInt32) ACE["AceType"];
DT.Rows.Add(Row);
DT.AcceptChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
return DT;
}

Categories