Share via


如何:啟用或停用伺服器網路通訊協定 (SQL Server PowerShell)

SQL Server 安裝程式會安裝 TCP 和具名管道網路通訊協定,但是可能不會啟用它們。您可以使用下列 PowerShell 指令碼或 SQL Server 組態管理員來啟用或停用網路通訊協定。您必須停止並重新啟動 SQL Server Database Engine,才能讓通訊協定變更生效。

如需有關 PowerShell 的一般資訊,請參閱<SQL Server PowerShell 概觀>。如需有關如何使用 SQL Server 組態管理員來管理通訊協定的詳細資訊,請參閱<如何:啟用或停用伺服器網路通訊協定 (SQL Server 組態管理員)>。

SQL Server PowerShell (SQLPS.exe) 公用程式會啟動 PowerShell 工作階段並且載入和註冊 SQL Server PowerShell 提供者與指令程式。執行 PowerShell (PowerShell.exe) 而非 SQL Server PowerShell 時,請先執行下列陳述式來手動載入必要的組件。

# Load the assemblies
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")

下列指令碼會啟用通訊協定。若要停用通訊協定,請將 IsEnabled 屬性設定為 $false。

若要使用 SQL Server PowerShell 來啟用伺服器網路通訊協定

  1. 使用管理員權限來開啟命令提示字元。

  2. 若要啟動 SQL Server PowerShell,請在命令提示字元中,輸入 sqlps.exe。

  3. 執行下列陳述式,即可同時啟用 TCP 和具名管道通訊協定。請將 <computer_name> 取代成執行 SQL Server 的電腦名稱。如果您要設定具名執行個體,請將 MSSQLSERVER 取代成執行個體名稱。

    $smo = 'Microsoft.SqlServer.Management.Smo.'
    $wmi = new-object ($smo + 'Wmi.ManagedComputer').
    
    # List the object properties, including the instance names.
    $Wmi
    
    # Enable the TCP protocol on the default instance.
    $uri = "ManagedComputer[@Name='<computer_name>']/ ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Tcp']"
    $Tcp = $wmi.GetSmoObject($uri)
    $Tcp.IsEnabled = $true
    $Tcp.Alter()
    $Tcp
    
    # Enable the named pipes protocol for the default instance.
    $uri = "ManagedComputer[@Name='<computer_name>']/ ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Np']"
    $Np = $wmi.GetSmoObject($uri)
    $Np.IsEnabled = $true
    $Np.Alter()
    $Np
    

若要設定本機電腦的通訊協定

  • 在本機執行此指令碼並且設定本機電腦時,SQL Server PowerShell 可能會用動態方式決定本機電腦名稱,讓指令碼更具彈性。若要擷取本機電腦名稱,請將設定 $uri 變數的程式碼行取代成下列程式碼行:

    $uri = "ManagedComputer[@Name='" + (get-item env:\computername).Value + "']/ServerInstance[@Name='MSSQLSERVER']/ServerProtocol[@Name='Tcp']"
    

若要使用 SQL Server PowerShell 來重新啟動 Database Engine

  • 啟用或停用通訊協定之後,您必須停止並重新啟動 Database Engine,才能讓變更生效。您可以執行下列陳述式,利用 SQL Server PowerShell 來停止並啟用預設執行個體。若要停止並啟動具名執行個體,請將 'MSSQLSERVER' 取代成 'MSSQL$<instance_name>'。

    # Get a reference to the ManagedComputer class.
    CD SQLSERVER:\SQL\<computer_name>
    $Wmi = (get-item .).ManagedComputer
    # Get a reference to the default instance of the Database Engine.
    $DfltInstance = $Wmi.Services['MSSQLSERVER']
    # Display the state of the service.
    $DfltInstance
    # Stop the service.
    $DfltInstance.Stop();
    # Wait until the service has time to stop.
    # Refresh the cache.
    $DfltInstance.Refresh(); 
    # Display the state of the service.
    $DfltInstance
    # Start the service again.
    $DfltInstance.Start();
    # Wait until the service has time to start.
    # Refresh the cache and display the state of the service.
    $DfltInstance.Refresh(); $DfltInstance