使用C#将计算机导入SCCM上的特定集合 [英] Importing a computer to a specific collection on SCCM using C#

查看:121
本文介绍了使用C#将计算机导入SCCM上的特定集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我给出的任务是创建一个应用程序,通过C#将计算机添加到System Center Configuration Manager 2012中的集合中。 (我正在使用C#,因为有一些限制阻止我使用PowerShell)。



使用SDK文档 - 我已经提供了一个基本功能,它添加了一个计算机到一个集合,但它很难遵循,因为我没有大量经验困扰我。



  public   static   int  AddNewComputer(WqlConnectionManager连接, string  netBiosName, string  smBiosGuid, string  macAddress) //  ,string ComputerName,string CollectionName) 
{
尝试
{
if (smBiosGuid == null & ;& macAddress = = null
{
throw new ArgumentNullException( 必须定义smBiosGuid或macAddress);
}

// 将macAddress重新格式化为:separator。
if string .IsNullOrEmpty(macAddress)== false
{
macAddress = macAddress.Replace( - );
}

// 创建计算机。
字典<字符串,对象> inParams = new Dictionary< string,object>();
inParams.Add( NetbiosName,netBiosName);
inParams.Add( SMBIOSGUID,smBiosGuid);
inParams.Add( MACAddress,macAddress);
inParams.Add( OverwriteExistingRecord);

IResultObject outParams = connection.ExecuteMethod(
SMS_Site
ImportMachineEntry
inParams);

// 添加到所有系统集合。
IResultObject集合= connection.GetInstance( SMS_Collection.collectionId ='SMS00001');
IResultObject collectionRule = connection.CreateEmbeddedObjectInstance( SMS_CollectionRuleDirect);
collectionRule [ ResourceClassName]。StringValue = SMS_R_System;
collectionRule [ ResourceID]。IntegerValue = outParams [ ResourceID]。IntegerValue;

字典<字符串,对象> inParams2 = new Dictionary< string,object>();
inParams2.Add( collectionRule,collectionRule);

collection.ExecuteMethod( AddMembershipRule,inParams2);

return outParams [ 的ResourceID] IntegerValue。
}
catch (SmsException e)
{
Console.WriteLine( 无法添加计算机 + e.Message);
throw ;
}
}





我很难看到我可以在哪里实现应用程序的实际计算机名称在运行时获得。以及修改计算机将添加到哪个集合的位置。



是否有人有此经验,因为在线支持对此非常小。

解决方案

这不是你问题的论坛,因为你的问题与C#没有任何关系,而是与SCCM及其内部有关的一切WMI课程。这里可能只有两位常客在SCCM做过任何工作。



但是,你很幸运,因为我是那些常客之一完成SCCM的大量工作并为其编写工具。



您不需要大部分示例代码。你最好不要废弃你所拥有的东西并从头开始重写。您需要一些通用函数来执行诸如按名称查找SMS_Collection对象并返回它的内容,以及在SMS_R_System WMI对象中通过计算机名称(称为NetBiosName)查找ResourceId的函数,连接到站点服务器上的站点WMI数据库,...



这些是将计算机添加到集合的步骤:



0)查找您要添加此计算机的SMS_Collection。坚持下去,稍后您将需要它。



1)您必须在SMS_R_System表中查找您尝试添加的计算机名称的ResourceId在网站服务器上。

      SELECT ResourceId FROM SMS_R_System WHERE NetbiosName =' computerName '



2)您使用ResourceId在站点服务器上创建SMS_CollectionRuleDirect对象。

      创建其中一个这些,你需要提供三个值:

          a)ResourceClassName,它总是SMS_R_System 。

           b)您在步骤1中获得的ResourceId。

            c)RuleName,通常只是一个包含您添加的计算机名称的字符串。



4)在SMS_Collection对象上得到f在步骤0中,调用AddMembershipRule方法并传入您在步骤2中创建的SMS_CollectionRuleDirect对象。您还将提供QueryId为0,因为您添加了直接成员身份规则。



5)对于要添加到同一集合的每台计算机,重复步骤1到4.



6)在步骤0中获取的SMS_CollectionObject上调用RequestRefesh 。



完成!



不,我不能给你我的代码,因为它被埋没了在一个图书馆里,我花了3个月写作,我不能在这里发布那么多代码。我也不拥有它,因为它属于我的雇主。


这是我用于Configuration Manager 2007的内容......



 使用系统; 
使用 System.Collections.Generic;
使用 System.IO;
使用 Microsoft.ConfigurationManagement.ManagementProvider;
使用 Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
使用 Microsoft.Win32;

命名空间 AddToCollection
{
class Program
{
static string CollectionName;
static string SiteServer;
static string SiteCode;
静态列表< string> MachineList;

静态 void Main( string [] args)
{
SiteServer = SCCM.GetDefaultConnectionInfo( ServerName );
SiteCode = SCCM.GetDefaultConnectionInfo( SiteCode);
ParseParams();
if (CollectionName.Length > 2 && MachineList.Count > 0
{
SCCM WKS = SCCM(SiteServer,SiteCode);
WKS.OpenConnection();
string CollectionId = WKS.GetCollectionId(CollectionName);
if (CollectionId.Length == 8
{
列表与LT;串GT; MachinesInCollection = WKS.GetCollection(CollectionId);
foreach string MachineName in MachineList)
{
if (MachinesInCollection.Contains(MachineName))
Console.WriteLine(MachineName + 已经在集合中。);
else
{
int ResourceId = WKS.GetResourceId(MachineName );
if (ResourceId > 1
{
if (WKS.AddToCollection(CollectionId,ResourceId))
Console.WriteLine(MachineName + 已添加。);
else
Console.WriteLine(MachineName + 无法将机器添加到集合中。);
}
}
}
}
其他
{
系统。 Threading.Thread.Sleep( 5000 );
Console.WriteLine( 找不到集合。);
Environment.Exit( 12 );
}
System.Threading.Thread.Sleep( 5000 );
Environment.Exit( 0 );
}
else
{
Console.WriteLine( 参数无效。);
Console.WriteLine( AddToCollection +
);
System.Threading.Thread.Sleep(5000);
Environment.Exit(87);
}
}

static void ParseParams()
{
MachineList = new List< string>();
foreach(环境中的字符串项)。 GetCommandLineArgs())
{
if(item.StartsWith(
/ )|| item.StartsWith( - ))
{
try
{
string param = item.Substring(1,item.IndexOf(
) - 1).ToUpper( );
string paramValue = item.Remove(0,item.IndexOf(
)+ 1);
if(param ==
SITESERVER || param == SERVER
SiteServer = paramValue;
if(param ==
SITECODE
SiteCode = paramValue;
if(param ==
MACHINENAME || param == HOSTNAME ||
param ==
COMPUTERNAME || param == MACHINE ||
param ==
HOST || param == COMPUTER
MachineList.Add(paramValue);
if(param ==
COLLECTION || param == COLLECTIONID ||
param ==
COLLECTIONNAME
CollectionName = paramValue;
if(param ==
FILE || param == FILENAME ||
param ==
LIST || param == MACHINELIST ||
param ==
HOSTLIST || param == COMPUTERLIST
{
foreach(File.ReadAllLines(paramValue)中的字符串ComputerName)
{
if(ComputerName.Trim()。Length> 0)
MachineList.Add(ComputerName.Trim()。ToUpper());
}
}
}
catch {}
}
}
}
}

public class SCCM
{
private WqlConnectionManager SiteServerConnection;
私有字符串SiteServerName,SiteServerCode;
private bool _IsConnected;

public delegate void ReportProgressHandler(string Message);
公共事件ReportProgressHandler ReportProgress;

public SCCM(string SiteServer,string SiteCode)
{
SiteServerName = SiteServer;
SiteServerCode = SiteCode;
_IsConnected = false;
}

public SCCM()
{
SiteServerName = GetDefaultConnectionInfo(
ServerName );
SiteServerCode = GetDefaultConnectionInfo(
SiteCode );
}

~SCCM()
{
CloseConnection();
}

public WqlConnectionManager GetConnectionObject()
{
返回SiteServerConnection;
}

public void OpenConnection()
{
if(!_IsConnected)
{
SiteServerConnection = new WqlConnectionManager();
SiteServerConnection.Connect(SiteServerName);
_IsConnected = true;
}
}

public void CloseConnection()
{
if(_IsConnected)
{
SiteServerConnection.Close() ;
_IsConnected = false;
}
}

public bool已连接
{
get {return _IsConnected; }
set {if(value)OpenConnection(); else CloseConnection(); }
}

公共静态字符串GetDefaultConnectionInfo(string ValueName)
{
RegistryKey ConfigMgrAdminKey = Registry.CurrentUser.OpenSubKey(
@
Software\Microsoft \ConfigMgr \Admin UI \MRU \DefaultSite );
if(ConfigMgrAdminKey == null)返回null;
string result = ConfigMgrAdminKey.GetValue(ValueName).ToString();
ConfigMgrAdminKey.Close();
返回结果;
}

公共字符串GetCollectionId(string CollectionName)
{
if(CollectionName.Length == 8)
{
if(CollectionName .StartsWith(SiteServerCode,StringComparison.CurrentCultureIgnoreCase))
{
string hexValue = CollectionName.Remove(0,3);
try
{
int decValue = int.Parse(hexValue,System.Globalization.NumberStyles.HexNumber);
if(decValue> = 1)
return CollectionName;
}
catch {}
}
}
string wql =
SELECT * FROM SMS_Collection WHERE Name = ' {0}' ;
IResultObject CollectionItems = SiteServerConnection.QueryProcessor.ExecuteQuery(String.Format(wql,CollectionName));
foreach(CollectionItems中的IResultObject项)
返回项[
CollectionId ] 。字符串值;
返回null;
}

private IResultObject查询(字符串WQL)
{
if(_IsConnected)
返回SiteServerConnection.QueryProcessor.ExecuteQuery(WQL);
else
返回null;
}

public int GetResourceId(string ComputerName)
{
try
{
// string wql =
SELECT名称FROM SMS_Collection WHERE CollectionID = ' SMS00001' AND Name = ' + ComputerName +' ;
// SMS_Collection可以包含无效的机器 - 使用SMS_FullCollectionMembership而不是
string wql =
SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID = ' < span class =code-string> SMS00001'
AND Name = ' + ComputerName +' ;
IResultObject ItemList = Query(wql);
double i = 0;
foreach(ItemList中的IResultObject项)
返回项[
ResourceID ] .IntegerValue;
}
catch {Console.WriteLine(未找到ComputerName +
); }
返回-1;
}

public List< string> GetCollection(string CollectionNameOrID)
{
List< string> SystemList = new List< string>();
CollectionNameOrID = GetCollectionId(CollectionNameOrID);
string wql =
SELECT Name FROM SMS_FullCollectionMembership WHERE CollectionID = ' {0}' ;
IResultObject ItemList = Query(String.Format(wql,CollectionNameOrID));
double i = 0;
foreach(ItemList中的IResultObject项)
{
SystemList.Add(item [
名称 ]的StringValue)。
if(ReportProgress!= null)
{
i + = 1;
ReportProgress(((i / ItemList.Count)* 100).ToString()+
);
}
}
返回SystemList;
}

public bool AddToCollection(string CollectionID,int ResourceID)
{
try
{

IResultObject collection = SiteServerConnection .GetInstance(
SMS_Collection.collectionId = ' + CollectionID +' );
IResultObject collectionRule = SiteServerConnection.CreateEmbeddedObjectInstance(
SMS_CollectionRuleDirect );

collectionRule [
ResourceClassName ]。StringValue = SMS_R_System ;
collectionRule [
ResourceID ]。IntegerValue = ResourceID;
// collectionRule [
Rule_Name ]。StringValue = RuleName;

字典<字符串,> Params = new Dictionary< string,>();
Params.Add(
collectionRule ,collectionRule);

collection.ExecuteMethod(
AddMembershipRule ,Params);

返回true;
}
catch(SmsException e)
{
return false;
}
}

}
}

< / string>< / string>< / string>< /串GT;< /串GT;< /串GT;


Hi All,

The task i have been given is creating an application that adds a computer into a collection in System Center Configuration Manager 2012 through C#. (I'm using C# as there is certain limitations stopping me from using powershell).

Using the SDK documentation - I have been supplied with a basic function that adds a computer to a collection but it is hard to follow and as im not massively experienced is troubling me.

public static int AddNewComputer(WqlConnectionManager connection, string netBiosName, string smBiosGuid, string macAddress)//, string ComputerName, string CollectionName)
        {
            try
            {
                if (smBiosGuid == null && macAddress == null)
                {
                    throw new ArgumentNullException("smBiosGuid or macAddress must be defined");
                }

                // Reformat macAddress to : separator.
                if (string.IsNullOrEmpty(macAddress) == false)
                {
                    macAddress = macAddress.Replace("-", ":");
                }

                // Create the computer.
                Dictionary<string, object> inParams = new Dictionary<string, object>();
                inParams.Add("NetbiosName", netBiosName);
                inParams.Add("SMBIOSGUID", smBiosGuid);
                inParams.Add("MACAddress", macAddress);
                inParams.Add("OverwriteExistingRecord", false);

                IResultObject outParams = connection.ExecuteMethod(
                    "SMS_Site",
                    "ImportMachineEntry",
                    inParams);

                // Add to All System collection.
                IResultObject collection = connection.GetInstance("SMS_Collection.collectionId='SMS00001'");
                IResultObject collectionRule = connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
                collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
                collectionRule["ResourceID"].IntegerValue = outParams["ResourceID"].IntegerValue;

                Dictionary<string, object> inParams2 = new Dictionary<string, object>();
                inParams2.Add("collectionRule", collectionRule);

                collection.ExecuteMethod("AddMembershipRule", inParams2);

                return outParams["ResourceID"].IntegerValue;
            }
            catch (SmsException e)
            {
                Console.WriteLine("failed to add the computer" + e.Message);
                throw;
            }
        }



I am struggling to see where I can implement the actual computer name which the application will gain at run time. And also where to modify which collection the computer will be added to.

Is there anybody with experience in this as the support online is very minimal for this.

解决方案

This isn't really the forum for your question as your question doesn't have anything to do with C# but, instead, everything to do with the internals of SCCM and its WMI classes. There's probably only two regular visitors around here who has done any work with SCCM.

But, you got lucky as I'm one of those "regular visitors" who has done extensive work with SCCM and writing tools for it.

You don't need most of your sample code. You'd be better off scrapping what you have and rewriting from scratch. You'll need a few "generic" functions to do stuff like look up a SMS_Collection object by name and return it, as well as one to look up a ResourceId by computer name (refered to as NetBiosName) in the SMS_R_System WMI objects, connect to the site WMI database on the site server, ...

These are the steps to add a computer to a collection:

0) Lookup the SMS_Collection you're adding this computer to. Hang on to this, you'll need it later.

1) You have to lookup the ResourceId for the computer name you're trying to add in the SMS_R_System table on the site server.
      "SELECT ResourceId FROM SMS_R_System WHERE NetbiosName='computerName'"

2) You use the ResourceId to create a SMS_CollectionRuleDirect object on the site server.
      To create one of these, you need to supply three values:
          a) The ResourceClassName, which is always going to be "SMS_R_System".
          b) The ResourceId you got in step 1.
          c) A RuleName, usually just a string containing the computer name your adding.

4) On the SMS_Collection object to got from step 0, call the AddMembershipRule method and pass in the SMS_CollectionRuleDirect object you created in step 2. You'll also supply a QueryId of 0 because your adding a Direct membership rule.

5) Repeat steps 1 through 4 for each computer you're adding to the same collection.

6) Call RequestRefesh on the SMS_CollectionObject you got from step 0.

Done!

No, I can't give you the code I have because it's buried within a libary I spent 3 months writing and I can't post that much code here. I also don't own it as it belongs to my employer.


here is what I am using for Configuration Manager 2007...

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
using Microsoft.Win32;

namespace AddToCollection
{
    class Program
    {
        static string CollectionName;
        static string SiteServer;
        static string SiteCode;
        static List<string> MachineList;

        static void Main(string[] args)
        {
            SiteServer = SCCM.GetDefaultConnectionInfo("ServerName");
            SiteCode = SCCM.GetDefaultConnectionInfo("SiteCode");
            ParseParams();
            if (CollectionName.Length > 2 && MachineList.Count > 0)
            {
                SCCM WKS = new SCCM(SiteServer, SiteCode);
                WKS.OpenConnection();
                string CollectionId = WKS.GetCollectionId(CollectionName);
                if (CollectionId.Length == 8)
                {
                    List<string> MachinesInCollection = WKS.GetCollection(CollectionId);
                    foreach (string MachineName in MachineList)
                    {
                        if (MachinesInCollection.Contains(MachineName))
                            Console.WriteLine(MachineName + " already in collection.");
                        else
                        {
                            int ResourceId = WKS.GetResourceId(MachineName);
                            if (ResourceId > 1)
                            {
                                if (WKS.AddToCollection(CollectionId, ResourceId))
                                    Console.WriteLine(MachineName + " added.");
                                else
                                    Console.WriteLine(MachineName + " failed to add machine to collection.");
                            }
                        }
                    }
                }
                else
                {
                    System.Threading.Thread.Sleep(5000);
                    Console.WriteLine("Collection not found.");
                    Environment.Exit(12);  
                }
                System.Threading.Thread.Sleep(5000);
                Environment.Exit(0);
            }
            else
            {
                Console.WriteLine("Invalid parameter.");
                Console.WriteLine("AddToCollection "+
                    ");
                System.Threading.Thread.Sleep(5000);
                Environment.Exit(87);
            }
        }

        static void ParseParams()
        {
            MachineList = new List<string>();
            foreach (string item in Environment.GetCommandLineArgs())
            {
                if (item.StartsWith("/") || item.StartsWith("-"))
                {
                    try
                    {
                        string param = item.Substring(1, item.IndexOf(":") - 1).ToUpper();
                        string paramValue = item.Remove(0, item.IndexOf(":")+1);
                        if (param=="SITESERVER" || param=="SERVER")
                            SiteServer = paramValue;
                        if (param == "SITECODE")
                            SiteCode = paramValue;
                        if (param == "MACHINENAME" || param == "HOSTNAME" ||
                            param == "COMPUTERNAME" || param == "MACHINE" ||
                            param == "HOST" || param == "COMPUTER")
                            MachineList.Add(paramValue);
                        if (param == "COLLECTION" || param == "COLLECTIONID" ||
                            param == "COLLECTIONNAME")
                            CollectionName = paramValue;
                        if (param == "FILE" || param == "FILENAME" ||
                            param == "LIST" || param == "MACHINELIST" ||
                            param == "HOSTLIST" || param == "COMPUTERLIST")
                        {
                            foreach (string ComputerName in File.ReadAllLines(paramValue))
                            {
                                if (ComputerName.Trim().Length > 0)
                                    MachineList.Add(ComputerName.Trim().ToUpper());
                            }
                        }
                    }
                    catch { }
                }
            }
        }
    }

    public class SCCM
    {
        private WqlConnectionManager SiteServerConnection;
        private string SiteServerName, SiteServerCode;
        private bool _IsConnected;

        public delegate void ReportProgressHandler(string Message);
        public event ReportProgressHandler ReportProgress;

        public SCCM(string SiteServer, string SiteCode)
        {
            SiteServerName = SiteServer;
            SiteServerCode = SiteCode;
            _IsConnected = false;
        }

        public SCCM()
        {
            SiteServerName = GetDefaultConnectionInfo("ServerName");
            SiteServerCode = GetDefaultConnectionInfo("SiteCode");
        }

        ~SCCM()
        {
            CloseConnection();
        }

        public WqlConnectionManager GetConnectionObject()
        {
            return SiteServerConnection;
        }

        public void OpenConnection()
        {
            if (!_IsConnected)
            {
                SiteServerConnection = new WqlConnectionManager();
                SiteServerConnection.Connect(SiteServerName);
                _IsConnected = true;
            }
        }

        public void CloseConnection()
        {
            if (_IsConnected)
            {
                SiteServerConnection.Close();
                _IsConnected = false;
            }
        }

        public bool Connected
        {
            get { return _IsConnected; }
            set { if (value) OpenConnection(); else CloseConnection(); }
        }

        public static string GetDefaultConnectionInfo(string ValueName)
        {
            RegistryKey ConfigMgrAdminKey = Registry.CurrentUser.OpenSubKey(
                    @"Software\Microsoft\ConfigMgr\Admin UI\MRU\DefaultSite");
            if (ConfigMgrAdminKey == null) return null;
            string result = ConfigMgrAdminKey.GetValue(ValueName).ToString();
            ConfigMgrAdminKey.Close();
            return result;
        }

        public string GetCollectionId(string CollectionName)
        {
            if (CollectionName.Length == 8)
            {
                if (CollectionName.StartsWith(SiteServerCode, StringComparison.CurrentCultureIgnoreCase))
                {
                    string hexValue = CollectionName.Remove(0, 3);
                    try
                    {
                        int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
                        if (decValue >= 1)
                            return CollectionName;
                    }
                    catch { }
                }
            }
            string wql = "SELECT * FROM SMS_Collection WHERE Name = '{0}'";
            IResultObject CollectionItems = SiteServerConnection.QueryProcessor.ExecuteQuery(String.Format(wql, CollectionName));
            foreach (IResultObject item in CollectionItems)
                return item["CollectionId"].StringValue;
            return null;
        }

        private IResultObject Query(string WQL)
        {
            if (_IsConnected)
                return SiteServerConnection.QueryProcessor.ExecuteQuery(WQL);
            else
                return null;
        }

        public int GetResourceId(string ComputerName)
        {
            try
            {
//                string wql = "SELECT Name FROM SMS_Collection WHERE CollectionID = 'SMS00001' AND Name='" + ComputerName + "'";
                // SMS_Collection can contain invalid machines - use SMS_FullCollectionMembership instead
                string wql = "SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID = 'SMS00001' AND Name='" + ComputerName + "'";
                IResultObject ItemList = Query(wql);
                double i = 0;
                foreach (IResultObject item in ItemList)
                    return item["ResourceID"].IntegerValue;
            }
            catch { Console.WriteLine(ComputerName + " not found."); }
            return -1;
        }

        public List<string> GetCollection(string CollectionNameOrID)
        {
            List<string> SystemList = new List<string>();
            CollectionNameOrID = GetCollectionId(CollectionNameOrID);
            string wql = "SELECT Name FROM SMS_FullCollectionMembership WHERE CollectionID = '{0}'";
            IResultObject ItemList = Query(String.Format(wql, CollectionNameOrID));
            double i = 0;
            foreach (IResultObject item in ItemList)
            {
                SystemList.Add(item["Name"].StringValue);
                if (ReportProgress != null)
                {
                    i += 1;
                    ReportProgress(((i / ItemList.Count) * 100).ToString() + "%");
                }
            }
            return SystemList;
        }

        public bool AddToCollection(string CollectionID, int ResourceID)
        {
            try
            {
                
                IResultObject collection = SiteServerConnection.GetInstance("SMS_Collection.collectionId='"+CollectionID+"'");
                IResultObject collectionRule = SiteServerConnection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");

                collectionRule["ResourceClassName"].StringValue = "SMS_R_System";
                collectionRule["ResourceID"].IntegerValue = ResourceID;
                //collectionRule["Rule_Name"].StringValue = RuleName;

                Dictionary<string,> Params = new Dictionary<string,>();
                Params.Add("collectionRule", collectionRule);

                collection.ExecuteMethod("AddMembershipRule", Params);

                return true;
            }
            catch (SmsException e)
            {
                return false;
            }
        }

    }
}

</string></string></string></string></string></string>


这篇关于使用C#将计算机导入SCCM上的特定集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆