Problems running WMI code through C# as scheduled task

R

Ryan McFall

I am running the following code as part of a scheduled task; the
objective of the code is to determine whether or not someone is logged
on to the workstation in an interactive session, and if so, if that
person is the same one as the one running the task.

ManagementScope ms = new ManagementScope(ManagementPath.DefaultPath);
System.Management.ManagementObject o;
SelectQuery q = new SelectQuery("Win32_LoggedOnUser"); // only
interactive logons
ManagementObjectSearcher query = new ManagementObjectSearcher(ms, q);

ManagementObjectCollection queryCollection = query.Get();
LinkedList<UserInfo> users = new LinkedList<UserInfo>();

foreach (ManagementObject loggedOnUser in queryCollection)
{
// Dependent is a Win32_LoginSession object
ManagementObject session = new
ManagementObject(loggedOnUser["Dependent"].ToString());
if ((session["LogonType"].ToString()) == "2") { // is
interactive?
// Antecedent is a Win32_Account object
Console.WriteLine("About to access the antecedent");
ManagementObject account = new

ManagementObject(loggedOnUser["Antecedent"].ToString());

String loginID = session["LogonID"].ToString();

String SID = account["SID"].ToString();


When this code is run by the logged on user within Visual Studio, it
works fine. But, when it's run as a scheduled task, running as
Administrator while another user is logged in, an NotFound exception
is thrown when trying to access the "SID" property of the account
object; actually, attempts to access any properties of this object
fail. Accesses to the properties of the session object are
successful.

Does anyone know why this would be the case?

Thanks in advance,
Ryan
 
G

Guest

It has been a long time since I dealt with Windows security, but I have a
fuzy memory that sometimes one has to enable one's permissions. See the
AdjustTokenPriveledges function:
http://msdn2.microsoft.com/en-us/library/aa375202.aspx.

This looks good at a glance:
http://msdn.microsoft.com/msdnmag/issues/05/03/TokenPrivileges/default.aspx

I find the best tool for debugging things like this can be the NT Event log.
Make sure your system is configured to log all security access errors and
you will see exactly what priveledge is tripping you up (if that is your
problem).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top