我可以用smo启动sql server浏览器服务吗?

时间:2011-11-07 15:35:03

标签: .net sql-server wmi smo

我需要从VB.Net程序枚举SQL Server。如果未启用SQL Browser服务,则会失败。默认安装似乎已将其禁用。

如何测试服务状态,如果需要,启用它并启动它?

1 个答案:

答案 0 :(得分:2)

您不一定需要SMO。您可以使用ServiceController类。以下是启动未运行服务的简单示例:

' don't forget to reference the System.ServiceProcess and Imports System.Management DLLs 

imports System
imports System.ServiceProcess
imports System.Management

public module MyModule
Sub Main()
    Dim serviceName as String = "SQLBrowser"
    Dim sc As ServiceController = New ServiceController(serviceName)


    ' make sure start mode is automatic
    Dim path As String = "Win32_Service.Name='" & serviceName & "'"
    Dim p As New ManagementPath(path)
    Dim ManagementObj As New ManagementObject(p)
    Dim parameters As Object() = New Object(0) {}
    Dim value As String = "Automatic"
    parameters(0) = value
    ManagementObj.InvokeMethod("ChangeStartMode", parameters)

    if sc.Status = ServiceControllerStatus.Stopped or sc.Status = ServiceControllerStatus.Paused then
        Console.WriteLine(serviceName + " is starting.")
        sc.Start()
    else
        Console.WriteLine(serviceName + " is running.")
    end if
End Sub

结束模块