Compartilhar via


Como Criar uma Janela de Manutenção para uma Coleção

A sua aplicação pode criar uma janela de manutenção Configuration Manager com as classes E propriedades da Classe WMI de Servidor SMS_CollectionSettings e da Classe WMI de Servidor SMS_ServiceWindow.

Para criar uma janela de manutenção

  1. Configure uma ligação ao Fornecedor de SMS. Para obter mais informações, veja Noções básicas do Fornecedor de SMS.

  2. Obtenha a instância de definições de coleção existente com o ID de coleção fornecido.

  3. Crie e preencha as propriedades de um novo objeto de janela de serviço com a classe classe WMI de Servidor SMS_ServiceWindow .

  4. Adicione o novo SMS_ServiceWindow objeto à instância de definições da coleção obtida anteriormente.

  5. Guarde a instância e as propriedades das definições da coleção.

Observação

O exemplo abaixo inclui passos adicionais, principalmente para lidar com a sobrecarga de lidar com os objetos da janela de manutenção, que são armazenados como objetos incorporados na instância de definições da coleção.

Exemplo

O método de exemplo seguinte cria uma janela de manutenção para uma coleção, partindo do princípio de que a instância da coleção pode ser modificada. Este pode não ser o caso em sites subordinados, em que as coleções pertencem aos sites principais.

Para obter informações sobre como chamar o código de exemplo, veja Chamar Configuration Manager Fragmentos de Código.


Sub CreateMaintenanceWindow(connection,                                 _
                            targetCollectionID,                         _
                            newMaintenanceWindowName,                   _
                            newMaintenanceWindowDescription,            _
                            newMaintenanceWindowServiceWindowSchedules, _
                            newMaintenanceWindowIsEnabled,              _
                            newMaintenanceWindowServiceWindowType)

    ' Build a query to get the specified collection.
     collectionSettingsQuery = "SMS_CollectionSettings.CollectionID='" & targetCollectionID & "'"

    ' Get the collection settings instance for the targetCollectionID.
    Set allCollectionSettings = connection.ExecQuery("Select * From SMS_CollectionSettings Where CollectionID = '" & targetCollectionID & "'")

    ' If a collection settings instance does not exist for the target collection, create one.
    If allCollectionSettings.Count = 0 Then
        Wscript.Echo "Creating collection settings instance."
        Set collectionSettingsInstance = connection.Get("SMS_CollectionSettings").SpawnInstance_
        collectionSettingsInstance.CollectionID = targetCollectionID
        collectionSettingsInstance.Put_
    End If

    ' Get the specific collection settings instance.
    Set collectionSettingsInstance = connection.Get("SMS_CollectionSettings.CollectionID='" & targetCollectionID &"'" )

    ' Create and populate a temporary SMS_ServiceWindow object with the new maintenance window values.
    Set tempServiceWindowObject = connection.Get("SMS_ServiceWindow").SpawnInstance_

    ' Populate temporary SMS_ServiceWindow object with the new maintenance window values.
    tempServiceWindowObject.Name = newMaintenanceWindowName
    tempServiceWindowObject.Description = newMaintenanceWindowDescription
    tempServiceWindowObject.ServiceWindowSchedules = newMaintenanceWindowServiceWindowSchedules
    tempServiceWindowObject.IsEnabled = newMaintenanceWindowIsEnabled
    tempServiceWindowObject.ServiceWindowType = newMaintenanceWindowServiceWindowType

    ' Populate the local array list with the existing service window objects (from the target collection).
    tempServiceWindowArray = collectionSettingsInstance.ServiceWindows

    ' Add the newly created service window object to the temporary array.
    ReDim Preserve tempServiceWindowArray (Ubound(tempServiceWindowArray) + 1)
    Set tempServiceWindowArray(Ubound(tempServiceWindowArray)) = tempServiceWindowObject

    ' Replace the existing service window objects from the target collection with the temporary array that includes the new service window.
    collectionSettingsInstance.ServiceWindows = tempServiceWindowArray

    ' Save the collection settings instance with the new service window object.
    collectionSettingsInstance.Put_

    ' Output success message.
    wscript.echo "New Maintenance Window created."

End Sub


public void CreateMaintenanceWindow(WqlConnectionManager connection,
                                    string targetCollectionID,
                                    string newMaintenanceWindowName,
                                    string newMaintenanceWindowDescription,
                                    string newMaintenanceWindowServiceWindowSchedules,
                                    bool newMaintenanceWindowIsEnabled,
                                    int newMaintenanceWindowServiceWindowType)
{
    try
    {
        // Create an object to hold the collection settings instance (used to check whether a collection settings instance exists).
        IResultObject collectionSettingsInstance = null;

        // Get the collection settings instance for the targetCollectionID.
        IResultObject allCollectionSettings = connection.QueryProcessor.ExecuteQuery("Select * from SMS_CollectionSettings where CollectionID='" + targetCollectionID + "'");

        // Enumerate the allCollectionSettings collection (there should be just one item) and save the instance.
        foreach (IResultObject collectionSetting in allCollectionSettings)
        {
            collectionSettingsInstance = collectionSetting;
        }

        // If a collection settings instance does not exist for the target collection, create one.
        if (collectionSettingsInstance == null)
        {
            collectionSettingsInstance = connection.CreateInstance("SMS_CollectionSettings");
            collectionSettingsInstance["CollectionID"].StringValue = targetCollectionID;
            collectionSettingsInstance.Put();
            collectionSettingsInstance.Get();
        }

        // Create a new array list to hold the service window object.
        List<IResultObject> tempServiceWindowArray = new List<IResultObject>();

        // Create and populate a temporary SMS_ServiceWindow object with the new maintenance window values.
        IResultObject tempServiceWindowObject = connection.CreateEmbeddedObjectInstance("SMS_ServiceWindow");

        // Populate temporary SMS_ServiceWindow object with the new maintenance window values.
        tempServiceWindowObject["Name"].StringValue = newMaintenanceWindowName;
        tempServiceWindowObject["Description"].StringValue = newMaintenanceWindowDescription;
        tempServiceWindowObject["ServiceWindowSchedules"].StringValue = newMaintenanceWindowServiceWindowSchedules;
        tempServiceWindowObject["IsEnabled"].BooleanValue = newMaintenanceWindowIsEnabled;
        tempServiceWindowObject["ServiceWindowType"].IntegerValue = newMaintenanceWindowServiceWindowType;

        // Populate the local array list with the existing service window objects (from the target collection).
        tempServiceWindowArray = collectionSettingsInstance.GetArrayItems("ServiceWindows");

        // Add the newly created service window object to the local array list.
        tempServiceWindowArray.Add(tempServiceWindowObject);

        // Replace the existing service window objects from the target collection with the temporary array that includes the new service window.
        collectionSettingsInstance.SetArrayItems("ServiceWindows", tempServiceWindowArray);

        // Save the new values in the collection settings instance associated with the target collection.
        collectionSettingsInstance.Put();
    }
    catch (SmsException ex)
    {
        Console.WriteLine("Failed. Error: " + ex.InnerException.Message);
        throw;
    }
}

O método de exemplo tem os seguintes parâmetros:

Parâmetro Tipo Descrição
connection

swebemServices
- Gerido: WqlConnectionManager
- VBScript: SWbemServices
Uma ligação válida ao Fornecedor de SMS.
targetCollectionID - Gerido: String
- VBScript: String
O ID da coleção.
newMaintenanceWindowName - Gerido: String
- VBScript: String
O nome da nova janela de manutenção.
newMaintenanceWindowDescription - Gerido: String
- VBScript: String
A descrição da nova janela de manutenção.
newMaintenanceWindowServiceWindowSchedules - Gerido: String
- VBScript: String
O serviço agenda para a nova janela de manutenção.
newMaintenanceWindowIsEnabled - Gerido: Boolean
- VBScript: Boolean
true se a nova janela de manutenção estiver ativada.
newMaintenanceWindowServiceWindowType - Gerido: Integer
- VBScript: Integer
Escreva para a nova janela de manutenção.

Compilando o código

O exemplo de C# requer:

Namespaces

System

System.Collections.Generic

System.ComponentModel

Microsoft.ConfigurationManagement.ManagementProvider

Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine

Assembly

adminui.wqlqueryengine

microsoft.configurationmanagement.managementprovider

Programação robusta

Para obter mais informações sobre o processamento de erros, veja About Configuration Manager Errors (Acerca dos Erros de Configuration Manager).

Segurança do .NET Framework

Para obter mais informações sobre como proteger aplicações Configuration Manager, veja Configuration Manager administração baseada em funções.

Confira também

About maintenance windowsSoftware distribution overviewAbout deploymentsObjects overviewHow to Connect to a Configuration Manager Provider using Managed CodeHow to Connect to a Configuration Manager Provider Using WMI SMS_CollectionSettings Server WMI Class SMS_ServiceWindow Server WMI Class WMI Class (Como Ligar a um Fornecedor de Configuration Manager com a Classe WMI de Servidor WMI SMS_ServiceWindow Classe WMI de Servidor WMI)Acerca das agendasComo Criar um Token de Agenda