Бөлісу құралы:


Управление службами и параметрами сети с помощью поставщика WMI

Область применения: SQL Server 2022 (16.x)

Поставщик WMI — это опубликованный интерфейс, используемый консолью управления Майкрософт (MMC) для управления службами и сетевыми протоколами SQL Server. В SMO ManagedComputer объект представляет поставщика WMI.

Объект ManagedComputer работает независимо от соединения, установленного с Server объектом к экземпляру SQL Server, и использует учетные данные Windows для подключения к службе WMI.

Примеры

Чтобы использовать любой пример кода, предоставленный, выберите среду программирования, шаблон и язык, в котором нужно создать приложение. Дополнительные сведения см. в статье "Создание проекта SMO Visual C# в Visual Studio .NET".

Для программ, использующих поставщик WMI SQL Server, необходимо включить Imports инструкцию для квалификации пространства имен WMI. Вставьте инструкцию после других инструкций Imports и перед любыми декларациями в приложении.

Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common
Imports Microsoft.SqlServer.Management.Smo.Wmi

Остановка и перезапуск службы SQL Server в Visual Basic

Этот пример кода показывает, как остановить и запустить службы с помощью объекта SMO ManagedComputer. Это обеспечивает интерфейс для поставщика WMI для управления конфигурацией.

'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 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

Включение протокола сервера с помощью строки URN в Visual Basic

В примере кода показано, как определить протокол сервера с помощью объекта URN, а затем включить протокол.

'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()

Включение протокола сервера с помощью строки URN в PowerShell

В примере кода показано, как определить протокол сервера с помощью объекта URN, а затем включить протокол.

#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()

Запуск и остановка службы в C#

Пример кода показывает, как остановить и запустить экземпляр 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 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();
}

Запуск и остановка службы в PowerShell

Пример кода показывает, как остановить и запустить экземпляр 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 instances running on this mc
foreach ($Item in $mc.Services) { $Item.Name }

#Get the default SQL Server database 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"