Friday, January 30, 2009

продолжаем мучать WMI

получаем пользователей с компа или домена(актив директории)
public static void GetUsers()
{
SelectQuery sQuery = new SelectQuery("Win32_UserAccount","Domain='CHAKS-PC'");

try
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

Console.WriteLine("User Accounts");
Console.WriteLine("");

foreach (ManagementObject mObject in mSearcher.Get())
{
Console.WriteLine(mObject["Name"]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadKey();
}

Получение группы


public static void GetGroups()
{
SelectQuery sQuery = new SelectQuery("Win32_Group", "Domain='CHAKS-PC'");

try
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

Console.WriteLine("Groups");
Console.WriteLine("");

foreach (ManagementObject mObject in mSearcher.Get())
{
Console.WriteLine(mObject["Name"]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadKey();
}

Решение выборка пользователей из группы


public static void GetUsers(String DomainName, String GroupName)
{
#region Build WMI query using SelectQuery
///
/// Alternate method for building query
/// Which I think is better approach
///

StringBuilder sBuilder = new StringBuilder("GroupComponent=");
sBuilder.Append('"');
sBuilder.Append("Win32_Group.Domain=");
sBuilder.Append("'");
sBuilder.Append(DomainName);
sBuilder.Append("'");
sBuilder.Append(",Name=");
sBuilder.Append("'");
sBuilder.Append(GroupName);
sBuilder.Append("'");
sBuilder.Append('"');
SelectQuery sQuery = new SelectQuery("Win32_GroupUser", sBuilder.ToString());
#endregion

///
/// Execute the query
/// Construct a ManagementPath from the PartComponent and check for ClassName
/// and extract the UserName
/// Depending on which method you used to build the query,
/// pass the String or SelectQuery object to ManagementObjectSearcher
///

try
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

foreach (ManagementObject mObject in mSearcher.Get())
{
ManagementPath path = new ManagementPath(mObject["PartComponent"].ToString());

if (path.ClassName == "Win32_UserAccount")
{
String[] names = path.RelativePath.Split(',');
Console.WriteLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace('"', ' ').Trim());
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadKey();
}

Добавляем безопасность

ConnectionOptions co = new ConnectionOptions();
co.Username = "Домен\Пользователь";
co.Impersonation = ImpersonationLevel.Impersonate;
co.Password = "Пароль пользователя";
string stringMachineName = "Компутер";
System.Management.ManagementScope mSearcher = new System.Management.ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2", co);

No comments:

Post a Comment