Gerenciando serviços e configurações de rede através do provedor do WMI

O provedor do WMI é uma interface publicada que é usada pelo Microsoft Management Console (MMC) para gerenciar os serviços e protocolos de rede do SQL Server. No SMO, o objeto ManagedComputer representa o Provedor do WMI.

O objeto ManagedComputer opera de forma independente da conexão estabelecida com o objeto Server para uma instância do SQL Server, e usa credenciais do Windows para se conectar ao serviço do WMI.

Exemplo

Para usar qualquer exemplo de código fornecido, será necessário escolher o ambiente de programação, o modelo de programação e a linguagem de programação para criar o aplicativo. Para mais informações, consulte "Como criar um projeto Visual Basic SMO no Visual Studio .NET" ou "Como criar um projeto Visual C# SMO no Visual Studio .NET" nos Manuais Online do SQL Server.

Para programas que usam o provedor WMI do SQL Server, inclua a instrução Imports para qualificar o namespace do WMI. Insira a instrução após outras instruções Imports, antes de qualquer declaração no aplicativo, como:

Imports Microsoft.SqlServer.Management.Smo

Imports Microsoft.SqlServer.Management.Common

Imports Microsoft.SqlServer.Management.Smo.Wmi

Interrompendo e reiniciando o serviço do Microsoft SQL Server para a instância do SQL Server no Visual Basic

Este exemplo de código mostra como interromper e iniciar serviços usando o objeto ManagedComputer SMO. Isso fornece uma interface ao Provedor WMI para Gerenciamento de Configuração.

'Declare and create an instance of the ManagedComputer object that represents the WMI Provider services.
Dim mc As ManagedComputer
mc = New ManagedComputer()
'Iterate through each service registered with the WMI Provider.
Dim svc As Service
For Each svc In mc.Services
    Console.WriteLine(svc.Name)
Next
'Reference the Microsoft SQL Server service.
svc = mc.Services("MSSQLSERVER")
'Stop the service if it is running and report on the status continuously until it has stopped.
If svc.ServiceState = ServiceState.Running Then
    svc.Stop()

    Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))
    Do Until String.Format("{0}", svc.ServiceState) = "Stopped"
        Console.WriteLine(String.Format("{0}", svc.ServiceState))
        svc.Refresh()
    Loop
    Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))
    'Start the service and report on the status continuously until it has started.
    svc.Start()
    Do Until String.Format("{0}", svc.ServiceState) = "Running"
        Console.WriteLine(String.Format("{0}", svc.ServiceState))
        svc.Refresh()
    Loop
    Console.WriteLine(String.Format("{0} service state is {1}", svc.Name, svc.ServiceState))

Else
    Console.WriteLine("SQL Server service is not running.")
End If

Habilitando um protocolo de servidor usando uma cadeia de caracteres URN no Visual Basic

O exemplo de código mostra como identificar um protocolo de servidor usando um objeto URN e, em seguida, habilitar o protocolo.

'Declare the ManagedComputer WMI interface.
Dim mc As New ManagedComputer()
'Create a URN object that represents the TCP server protocol.
Dim u As New Urn("ManagedComputer[@Name=MYPC']/ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Tcp']")
Declare the serverProtocol variable and return the ServerProtocol object.
Dim sp As ServerProtocol
sp = mc.GetSmoObject(u)
'Enable the protocol.
sp.IsEnabled = True
sp.Alter()

Habilitando um protocolo de servidor usando uma cadeia de caracteres URN no Visual C#

O exemplo de código mostra como identificar um protocolo de servidor usando um objeto URN e, em seguida, habilitar o protocolo.

{ 
   //Declare and create an instance of the ManagedComputer 
   //object that represents the WMI Provider services. 
   ManagedComputer mc; 
   mc = new ManagedComputer(); 
   //Iterate through each service registered with the WMI Provider. 
   Service svc; 
   foreach ( svc in mc.Services) { 
      Console.WriteLine(svc.Name); 
   } 
//Reference the Microsoft SQL Server service. 
   svc = mc.Services("MSSQLSERVER"); 
//Stop the service if it is running and report on the status
// continuously until it has stopped. 
   if (svc.ServiceState == ServiceState.Running) { 
      svc.Stop(); 
      Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState)); 
      while (!(string.Format("{0}", svc.ServiceState) == "Stopped")) { 
         Console.WriteLine(string.Format("{0}", svc.ServiceState)); 
          svc.Refresh(); 
      } 
      Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState)); 
//Start the service and report on the status continuously 
//until it has started. 
      svc.Start(); 
      while (!(string.Format("{0}", svc.ServiceState) == "Running")) { 
         Console.WriteLine(string.Format("{0}", svc.ServiceState)); 
         svc.Refresh(); 
      } 
      Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState)); 
   } 
   else { 
      Console.WriteLine("SQL Server service is not running."); 
   } 
}