Compartir a través de


Administración de servicios y configuración de red mediante el proveedor WMI

El proveedor WMI es una interfaz publicada que usa Microsoft Management Console (MMC) para administrar los servicios y protocolos de red de SQL Server. En SMO, el ManagedComputer objeto representa el proveedor WMI.

El ManagedComputer objeto funciona independientemente de la conexión establecida con el Server objeto a una instancia de SQL Server y usa credenciales de Windows para conectarse al servicio WMI.

Ejemplo

Para usar cualquier ejemplo de código que se proporcione, tendrá que elegir el entorno de programación, la plantilla de programación y el lenguaje de programación en el que se va a crear la aplicación. Para obtener más información, vea "How to: Create a Visual Basic SMO Project in Visual Studio .NET" o "How to: Create a Visual C# SMO Project in Visual Studio .NET" in SQL Server Books Online.

Para los programas que usan el proveedor WMI de SQL Server, debe incluir la Imports instrucción para calificar el espacio de nombres WMI. Inserte la instrucción después de las demás Imports instrucciones, antes de cualquier declaración en la aplicación, como:

Imports Microsoft.SqlServer.Management.Smo

Imports Microsoft.SqlServer.Management.Common

Imports Microsoft.SqlServer.Management.Smo.Wmi

Detención y reinicio del servicio Microsoft SQL Server a la instancia de SQL Server en Visual Basic

En este ejemplo de código se muestra cómo detener e iniciar servicios mediante el objeto SMO ManagedComputer . Esto proporciona una interfaz al proveedor WMI para la administración de configuración.

Habilitación de un protocolo de servidor mediante una cadena URN en Visual Basic

En el ejemplo de código se muestra cómo identificar un protocolo de servidor mediante un objeto URN y, a continuación, habilitar el protocolo.

'This program must run with administrator privileges.  
        '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='V-ROBMA3']/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  
  
        'propagate back to the service  
        sp.Alter()  

Habilitación de un protocolo de servidor mediante una cadena URN en PowerShell

En el ejemplo de código se muestra cómo identificar un protocolo de servidor mediante un objeto URN y, a continuación, habilitar el protocolo.

#This example shows how to identify a server protocol using a URN object, and then enable the protocol  
#This program must run with administrator privileges.  
  
#Load the assembly containing the classes used in this example  
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")  
  
#Get a managed computer instance  
$mc = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer  
  
#Create a URN object that represents the TCP server protocol  
#Change 'MyPC' to the name of the your computer   
$urn = New-Object -TypeName Microsoft.SqlServer.Management.Sdk.Sfc.Urn -argumentlist "ManagedComputer[@Name='MyPC']/ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Tcp']"  
  
#Get the protocol object  
$sp = $mc.GetSmoObject($urn)  
  
#enable the protocol on the object  
$sp.IsEnabled = $true  
  
#propagate back to actual service  
$sp.Alter()  

Inicio y detención de un servicio en Visual C#

En el ejemplo de código se muestra cómo detener e iniciar una instancia de SQL Server.

{   
   //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.   
  
   foreach (Service svc in mc.Services)  
   {   
      Console.WriteLine(svc.Name);   
   }   
//Reference the Microsoft SQL Server service.   
  Service Mysvc = mc.Services["MSSQLSERVER"];   
//Stop the service if it is running and report on the status  
// continuously until it has stopped.   
   if (Mysvc.ServiceState == ServiceState.Running) {   
      Mysvc.Stop();   
      Console.WriteLine(string.Format("{0} service state is {1}", Mysvc.Name, Mysvc.ServiceState));   
      while (!(string.Format("{0}", Mysvc.ServiceState) == "Stopped")) {   
         Console.WriteLine(string.Format("{0}", Mysvc.ServiceState));   
          Mysvc.Refresh();   
      }   
      Console.WriteLine(string.Format("{0} service state is {1}", Mysvc.Name, Mysvc.ServiceState));   
//Start the service and report on the status continuously   
//until it has started.   
      Mysvc.Start();   
      while (!(string.Format("{0}", Mysvc.ServiceState) == "Running")) {   
         Console.WriteLine(string.Format("{0}", Mysvc.ServiceState));   
         Mysvc.Refresh();   
      }   
      Console.WriteLine(string.Format("{0} service state is {1}", Mysvc.Name, Mysvc.ServiceState));  
      Console.ReadLine();  
   }   
   else {   
      Console.WriteLine("SQL Server service is not running.");  
      Console.ReadLine();  
   }   
}  

Inicio y detención de un servicio en PowerShell

En el ejemplo de código se muestra cómo detener e iniciar una instancia de SQL Server.

#Load the assembly containing the objects used in this example  
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")  
  
#Get a managed computer instance  
$mc = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer  
  
#List out all sql server instnces running on this mc  
foreach ($Item in $mc.Services){$Item.Name}  
  
#Get the default sql server datbase engine service  
$svc = $mc.Services["MSSQLSERVER"]  
  
# for stopping and starting services PowerShell must run as administrator  
  
#Stop this service  
$svc.Stop()  
$svc.Refresh()  
while ($svc.ServiceState -ne "Stopped")  
{  
$svc.Refresh()  
$svc.ServiceState  
}  
"Service" + $svc.Name + " is now stopped"  
"Starting " + $svc.Name  
$svc.Start()  
$svc.Refresh()  
while ($svc.ServiceState -ne "Running")  
{  
$svc.Refresh()  
$svc.ServiceState  
}  
$svc.ServiceState  
"Service" + $svc.Name + "is now started"

Véase también

Conceptos del proveedor WMI para la administración de configuración