Thursday, October 13, 2011

Using SCCM client center functionality to import local policy

Tired of waiting for collection evaluation and policy updates when advertising programs in SCCM? There is a function in SCCM client center that imports local machine policies, but it requires that an elevated user runs the program and there is not batch functionality.

By referencing the smsclictr.automation.dll this functionality can be reused to build workflow activities/batch programs that calls the same logic as SCCM client center uses. Example code:


SMSClient client = new SMSClient(computerName);
client.Connection.Connect();
if (client.Connection.mScope.IsConnected)
{
//Connect to the clients managementPoint SQL server
SqlConnectionStringBuilder sqlConnectionBuilder = new SqlConnectionStringBuilder("Integrated Security=True");
sqlConnectionBuilder.DataSource = client.ManagementPoint;
sqlConnectionBuilder.InitialCatalog = "SMS_" + client.SiteCode;

SqlConnection sqlConnection = new SqlConnection(sqlConnectionBuilder.ToString());
try
{
sqlConnection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT PolicyID, Body FROM Policy WHERE (PolicyID LIKE '%" + advertisementID + "%') ORDER BY PolicyID";
command.Connection = sqlConnection;

SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
byte[] policyBody = dataReader[1] as byte[];
client.SoftwareDistribution.ImportSCCMPolicy(policyBody, false);
Logging.Log("Policy imported on computer '" + computerName + "' (AdvertisementID: " + advertisementID + ")", System.Diagnostics.EventLogEntryType.Information);
break;
}
sqlConnection.Close();
}
catch (Exception ex)
{
Logging.Log("Failed to get policy from SQL for advertisement '" + advertisementID + "'. Error: " + ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
}
}