I have this code to enable parental control in windows:
System.Security.Principal.NTAccount myNTAccount = new System.Security.Principal.NTAccount("username");
System.Security.Principal.SecurityIdentifier mySecurityIdentifier = (System.Security.Principal.SecurityIdentifier)myNTAccount.Translate(typeof(System.Security.Principal.SecurityIdentifier));
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2\\Applications\\WindowsParentalControls", "SELECT * FROM WpcUserSettings where SID='" + mySecurityIdentifier.ToString() + "'");
foreach (ManagementObject queryObj in searcher.Get())
{
queryObj["AppRestrictions"] = true;
queryObj["HourlyRestrictions"] = true;
queryObj["LoggingRequired"] = false;
//queryObj["LogonHours"] = ;
//queryObj["OverrideRequests"] = ;
queryObj["WpcEnabled"] = true;
queryObj.Put();
}
By this, parental control enabled, but how can i set Program limits to define allowed programs?
I found that it is related to RestrictRun registry key:
SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
it explaned in this address:
https://www.howtogeek.com/howto/8739/restrict-users-to-run-only-specified-programs-in-windows-7/
Related
I'm trying to change the printer properties, SpoolEnabled & KeepPrintedJobs, using C#. I tried using the win32_printer but the SpoolEnabled value didn't change. I'm using .NET windows forms (4.6) & Windows 10.
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer Where Default = True");
ManagementObjectCollection printerCollection = new ManagementObjectSearcher(query).Get();
if (printerCollection.Count > 0)
{
foreach (ManagementObject printer in printerCollection)
{
PropertyDataCollection printerProperties = printer.Properties;
if ((bool)printerProperties["Default"].Value)
{
printerProperties["SpoolEnabled"].Value = true;
printer.Put();
}
}
}
Also, I tried using the following code with no success:
ManagementPath mPath = new ManagementPath("//./root/cimv2");
mPath.RelativePath = "Win32_Printer.DeviceID=\"" + PrinterName + "\"";
ManagementObject Printer = new ManagementObject(mPath);
string oldname = Printer.Properties["SpoolEnabled"].Value.ToString();
Printer.Properties["SpoolEnabled"].Value = true;
Printer.Put();
What library should I use, using c#, to change the SpoolEnabled & KeepPrintedJobs properties?
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 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
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.
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;
}
}