I'm running into an odd issue retrieving printer port addresses.
When I get all the entries in Win32_TCPIPPrinterPort, the HostAddress field (which should have the IP address) is usually blank/null, only the port name has a value. To make it a bit stranger, if a particular port is not in use by any printer, THEN the HostAddress will have the the proper value.
The C# code is simple, and results in something like this;
IP_192.168.1.100,
printerportxyz,
richTextBox1.Clear();
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_TCPIPPrinterPort");
foreach (ManagementObject port in portSearcher.Get())
{
richTextBox1.AppendText(
String.Format("Name: {0} HostAddress: {1}",
port["Name"],
port["HostAddress"])
);
}
I also tried the same thing in WSH/VBS, and saw the same behavior.
I ended up having to re-visit this, and making another attempt. I found that the built-in prnport.vbs managment script had no issues - looking into it I saw that while establishing its WMI connection it had oService.Security_.Priveleges.AddAsString "SeLoadDriverPrivilege"
the solution in C# ended up specifying the WMI ConnectionOptions and setting EnablePrivileges to true. Then the HostAdress was no longer null for unused or in-use ports.
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.EnablePrivileges = true;
ManagementScope mgmtScope = new ManagementScope("root\\CIMV2", connOptions);
mgmtScope.Connect();
ObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort");
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mgmtScope, objQuery);
foreach (ManagementObject mo in moSearcher.Get())
{
Console.WriteLine(String.Format("PortName={0} HostAddress={1}", mo["Name"], mo["HostAddress"]));
}
Related
I am trying to create an application that uses WMI to retrieve information about a computer on my local network. When I run it, I get an access denied error. Here is the code:
private void GetHDDdetails()
{
ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
options.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope oMs = new ManagementScope("\\\\remoteHostName\\root\\cimv2", options);
ObjectQuery oQuery = new ObjectQuery("SELECT Size FROM Win32_DiskDrive");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oCollection = oSearcher.Get();
foreach (ManagementObject obj in oCollection)
{
hddBox.Text = obj["Size"].ToString();
}
}
I have replaced some of the info above, such as user name and password, with placeholders for this post.
Some of the things I have tried is this: Disabling firewall on both machines, making sure TCP NetBIOS service and RCP and WMI services are running on both. The account I am using is an administrator on the local computer. Everything I have found online tells me to check these, but it is obviously something else.
If someone can point me in the right direction, that would be great.
Please check using wbemtest that you can access the information from remote machine. And i hope you are replacing remoteHostName properly.
And make changes to authentication level, if you can.
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
I'm trying to delete a network printer that was removed from the printserver.
I'm using this code for deleting installed printers:
public void unmapPrinter()
{
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath, options);
scope.Connect();
ManagementClass win32Printer = new ManagementClass("Win32_Printer");
ManagementObjectCollection printers = win32Printer.GetInstances();
foreach (ManagementObject printer in printers)
{
printer.Delete();
}
}
This works well with normal printers, but there is one that was removed from the printerserver that return me "Access Denied". Some one know this problem?
Even windows can uninstal that printer, when i try to delete that from "Printers and Hardware" it tell me that the printer is in warning.
I want to open process pon remote machine, this remote machine is inside local network.
I try this command and in the remote machine nothing happen, this user that i connect with have administrators rights.
Both machines running Windows 7
static void Main(string[] args)
{
try
{
//Assign the name of the process you want to kill on the remote machine
string processName = "notepad.exe";
//Assign the user name and password of the account to ConnectionOptions object
//which have administrative privilege on the remote machine.
ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = #"MyDomain\MyUser";
connectoptions.Password = "12345678";
//IP Address of the remote machine
string ipAddress = "192.168.0.100";
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2", connectoptions);
//Define the WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
object[] methodArgs = { "notepad.exe", null, null, 0 };
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
//process.InvokeMethod("Terminate", null);
process.InvokeMethod("Create", methodArgs);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
//Log exception in exception log.
//Logger.WriteEntry(ex.StackTrace);
Console.WriteLine(ex.StackTrace);
}
}
you are not opening a process with that code but you are enumerating all the running process named "iexplore.exe" and close them.
I think an easier, better way is to use SysInternals PsExec or the Task Scheduler API
If you want to use WMI your code should look like this:
object theProcessToRun = { "YourFileHere" };
ManagementClass theClass = new ManagementClass(#"\\server\root\cimv2:Win32_Process");
theClass.InvokeMethod("Create", theProcessToRun);
----------In reply to your comment------------------
First of all you need to change your attitude and approach to coding and read the code that your are copy/pasting.
Then you should study a little more about programming languages.
No I will not write the code for you. I gave you an hint to point to the right direction. now it is your turn to develop it. Have fun!!
This is script that i did for my company before this using vbs script. can search the net to convert it to C# or etc. Fundamental of the steps and how to start a service using WMI. Have a nice coding and have fun.
sUser = "TESTDomain\T-CL-S"
sPass = "Temp1234"
Set ServiceSet = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service where Name = 'netlogon'")
For Each Service In ServiceSet
Service.StopService
Service.Change "netlogon",Service.PathName, , ,"Automatic",false,sUser,sPass
Service.StartService
Next
Set Service = Nothing
Set ServiceSet = Nothing
We have 6 Citrix Servers. I'm trying to find out if Remote Logons are enabled/disabled.
I plan to put this onto of a webpage to display and green icon if they are or red if they aren't.
I've managed to connect to the machines and pull operating system information etc.. However when i try and connect to view the TerminalServiceSetting information.. i get an Invalid Class error.
Here is my code.
ManagementScope scope = new ManagementScope("\\\\MACHINENAME\\ROOT\\cimv2");
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
Label1.Text = m["AllowTSConnections"].ToString();
}
If anyone can shed some light on it that would be great.
Thanks
Update:
I have now found the code (i think) that checks to see if remote connections are enabled or disabled.
ManagementScope scope =
new ManagementScope("\\\\MACHINENAME\\root\\CIMV2\\TerminalServices",con);
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
if (m["AllowTSConnections"].ToString() == "1")
{
Redicon.Visible = false;
}
else
{
Greenicon.Visible = false;
}
}
However when i run the code i get returned "1".. which is fine. However if i deny remote logins on the server and re run the code it stays at 1..
Any ideas?
You need to be sure that the server provide the TerminalServiceSetting information. WMI uses unmanaged code because not all servers and their configurations provide all information.
You can use Mgmtclassgen to generate managed code and at the same time make sure that the server provides the information.
Sorted!!!
I was looking up the wrong field.
the correct one is :
Label1.Text = "Remote Connections: " + m["Logons"].ToString();
I want to get id processor in .NET with WMI but when I'm using the get() method from the ManagementObjectSearcher, I'm getting an out of memory exception ...
If you want to take a look from the code see below :
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"select * from Win32_Processor");
foreach (ManagementObject share in searcher.Get())
foreach (PropertyData PC in share.Properties)
if (PC.Name.Equals("ProcessorId"))
return (string)PC.Value;
return null;
This code works on others computers but not on mine ...
I'm using windows 7.
What is the problem ?
I tried to restart WMI service and that not resolve my problem :(
There are several reasons which could cause out of memory exception.
possible memory leak in WMI, source:
http://brooke.blogs.sqlsentry.net/2010/02/win32service-memory-leak.html
check whether you have permission(s), that would explain why does your code work on some computers and why doesn't on yours.
run your code as Administrator (for debugging start VS as Administrator)
Here is an other code snippet, try this one as well... who knows
Sample:
public static String GetCPUId()
{
String processorID = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"Select * FROM WIN32_Processor");
ManagementObjectCollection mObject = searcher.Get();
foreach (ManagementObject obj in mObject)
{
processorID = obj["ProcessorId"].ToString();
}
return processorID;
}
Source: WIN32_Processor::Is ProcessorId Unique for all computers