Como importar um driver do Windows descrito por um arquivo INF para Configuration Manager

Você pode importar um driver do Windows descrito por um arquivo (.inf), em Configuration Manager, usando o Método CreateFromINF em Class SMS_Driver.

Para importar um driver do Windows

  1. Configure uma conexão com o Provedor de SMS. Para obter mais informações, confira Os fundamentos do Provedor de SMS.

  2. Chame o Método CreateFromINF na classe SMS_Driver para obter o objeto base de gerenciamento de classe WMI do servidor SMS_Driver inicial.

  3. Crie uma instância de SMS_Driver usando o objeto base de gerenciamento.

  4. Preencha o SMS_Driver objeto.

  5. Confirme o SMS_Driver objeto.

Exemplo

O método de exemplo a seguir cria um SMS_Driver objeto para um driver windows usando o caminho e o nome do arquivo fornecidos. O exemplo também habilita o driver definindo o valor da IsEnabled propriedade como true. A função GetDriverName auxiliar é usada para obter o nome do driver do pacote de driver XML.

Observação

O path parâmetro deve ser fornecido como um caminho de rede UNC (Convenção Universal de Nomenclatura), por exemplo, \\localhost\Drivers\ATIVideo\.

No exemplo, a LocaleID propriedade é codificada em código para inglês (EUA). Se você precisar da localidade para não-EUA. instalações, você pode obtê-lo na propriedade classe LocaleIDWMI do servidor SMS_Identification.

Para obter informações sobre como chamar o código de exemplo, consulte Chamando Configuration Manager Snippets de Código.

Sub ImportINFDriver(connection, path, name)  

    Dim driverClass  
    Dim inParams  
    Dim outParams  

    On Error Resume Next  

    ' Obtain an instance of the class   
    ' using a key property value.  

    Set driverClass = connection.Get("SMS_Driver")  

    ' Obtain an InParameters object specific  
    ' to the method.  
    Set inParams = driverClass.Methods_("CreateFromINF"). _  
        inParameters.SpawnInstance_()  

    ' Add the input parameters.  
    inParams.Properties_.Item("DriverPath") =  path  
    inParams.Properties_.Item("INFFile") =  name  

    ' Call the method.  
    ' The OutParameters object in outParams  
    ' is created by the provider.  
    Set outParams = connection.ExecMethod("SMS_Driver", "CreateFromINF", inParams)  

   If Err <> 0 Then  
        Wscript.Echo "Failed to add to the driver catalog: " + path + "\" + name  
        Exit Sub  
    End If      

    outParams.Driver.IsEnabled =  True  

    Dim LocalizedSettings(0)  
    Set LocalizedSettings(0) = connection.Get("SMS_CI_LocalizedProperties").SpawnInstance_()  
    LocalizedSettings(0).Properties_.item("LocaleID") =  1033   
    LocalizedSettings(0).Properties_.item("DisplayName") = _  
            GetDriverName(outParams.Driver.SDMPackageXML, "//DisplayName", "Text")  

    LocalizedSettings(0).Properties_.item("Description") = ""          
    outParams.Driver.LocalizedInformation = LocalizedSettings  

    ' Save the driver.  
    outParams.Driver.Put_  

End Sub  

Function GetDriverName(xmlContent, nodeName, attributeName)  
    ' Load the XML Document  
    Dim attrValue  
    Dim XMLDoc  
    Dim objNode  
    Dim displayNameNode  

    attrValue = ""  
    Set XMLDoc = CreateObject("Microsoft.XMLDOM")       
    XMLDoc.async = False  
    XMLDoc.loadXML(xmlContent)  

    'Check for a successful load of the XML Document.  
    If xmlDoc.parseError.errorCode <> 0 Then  
        WScript.Echo vbcrlf & "Error loading XML Document. Error Code : 0x" & hex(xmldoc.parseerror.errorcode)  
        WScript.Echo "Reason: " & xmldoc.parseerror.reason  
        WScript.Echo "Parse Error line " & xmldoc.parseError.line & ", character " & _  
                      xmldoc.parseError.linePos & vbCrLf & xmldoc.parseError.srcText  

        GetXMLAttributeValue = ""          
    Else  
        ' Select the node  
        Set objNode = xmlDoc.SelectSingleNode(nodeName)  

        If Not objNode Is Nothing Then  
            ' Found the element, now just pick up the Text attribute value  
            Set displayNameNode = objNode.attributes.getNamedItem(attributeName)  
            If Not displayNameNode Is Nothing Then  
               attrValue = displayNameNode.value  
            Else  
               WScript.Echo "Attribute not found"  
            End If  
        Else  
            WScript.Echo "Failed to locate " & nodeName & " element."  
        End If  
    End If  

    ' Save the results  
    GetDriverName = attrValue  
End Function  
public void ImportInfDriver(  
    WqlConnectionManager connection,   
    string path,   
    string name)  
{  
    try  
    {  
        Dictionary<string, object> inParams = new Dictionary<string, object>();  

        // Set up parameters for the path and file name.  
        inParams.Add("DriverPath", path);  
        inParams.Add("INFFile", name);  

        // Import the INF file.  
        IResultObject result = connection.ExecuteMethod("SMS_Driver", "CreateFromINF", inParams);  

        // Create the SMS_Driver driver instance from the management base object returned in result["Driver"].  
        IResultObject driver = connection.CreateInstance(result["Driver"].ObjectValue);  

        // Enable the driver.  
        driver["IsEnabled"].BooleanValue = true;  

        List<IResultObject> driverInformationList = driver.GetArrayItems("LocalizedInformation");  

        // Set up the display name and other information.  
        IResultObject driverInfo = connection.CreateEmbeddedObjectInstance("SMS_CI_LocalizedProperties");  
        driverInfo["DisplayName"].StringValue = GetDriverName(driver);  
        driverInfo["LocaleID"].IntegerValue = 1033;  
        driverInfo["Description"].StringValue = "";  

        driverInformationList.Add(driverInfo);  

        driver.SetArrayItems("LocalizedInformation", driverInformationList);  

        // Commit the SMS_Driver object.  
        driver.Put();  
    }  
    catch (SmsException e)  
    {  
        Console.WriteLine("Failed to import driver: " + e.Message);  
        throw;  
    }  
}  

public string GetDriverName(IResultObject driver)          
{  
    // Extract   
    XmlDocument sdmpackage = new XmlDocument();  

    sdmpackage.LoadXml(driver.Properties["SDMPackageXML"].StringValue);  

    // Iterate over all the <DisplayName/> tags.  
    foreach (XmlNode displayName in sdmpackage.GetElementsByTagName("DisplayName"))           
    {                  
    // Grab the first one with a Text attribute not equal to null.  
        if (displayName != null && displayName.Attributes["Text"] != null    
            && !string.IsNullOrEmpty(displayName.Attributes["Text"].Value))    
        {                        
                // Return the DisplayName text.  
                return displayName.Attributes["Text"].Value;      
        }              
    }   
    // Default the driverName to the UniqueID.  
    return driver["CI_UniqueID"].StringValue;         
 }  

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

Parâmetro Tipo Descrição
connection -Gerenciado: WqlConnectionManager
- VBScript: SWbemServices
Uma conexão válida com o provedor de SMS.
path -Gerenciado: String
-Vbscript: String
Um caminho de rede UNC válido para a pasta que contém o conteúdo do driver. Por exemplo, \\Servers\Driver\VideoDriver.
name -Gerenciado: String
-Vbscript: String
O nome do arquivo .inf. Por exemplo, ATI.inf.

Compilando o código

Este exemplo de C# requer:

Namespaces

System

System.Collections.Generic

System.Text

Microsoft. ConfigurationManagement.ManagementProvider

Microsoft. ConfigurationManagement.ManagementProvider.WqlQueryEngine

Assembly

microsoft.configurationmanagement.managementprovider

adminui.wqlqueryengine

Programação robusta

Para obter mais informações sobre o tratamento de erros, consulte Sobre erros de Configuration Manager.

Segurança do .NET Framework

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

Confira também

Método CreateFromINF na classe SMS_Driver
Classe WMI do servidor SMS_Driver
Como especificar as plataformas com suporte para um driver