在 SQL Server 無人值守安裝中設定靜態 TCP 連接埠

在 SQL Server 無人值守安裝中設定靜態 TCP 連接埠

我使用應答檔案無人值守安裝了 SQL Server 2016 .INI。在我的應答文件中,我像這樣啟用 TCP:

; Specify 0 to disable or 1 to enable the TCP/IP protocol. 
TCPENABLED="1"

安裝完成後,我還使用 PowerShell 腳本建立一個別名。到目前為止,一切都很好。但是,SQL Server 實例安裝時啟用了動態端口,並且我在應答文件中看不到指定靜態 TCP 連接埠(我想使用標準 1433)的方法。因此別名不起作用。

如何透過應答檔案或使用 PowerShell 設定靜態 TCP 連接埠?

答案1

經過長時間尋找可行的解決方案,我想出了這個 PowerShell 函數,它可以設定特定 SQL Server 實例的 TCP 連接埠:

function SetPort($instance, $port)
{
    # fetch the WMI object that contains TCP settings; filter for the 'IPAll' setting only
    # note that the 'ComputerManagement13' corresponds to SQL Server 2016
    $settings = Get-WmiObject `
        -Namespace root/Microsoft/SqlServer/ComputerManagement13 `
        -Class ServerNetworkProtocolProperty `
        -Filter "InstanceName='$instance' and IPAddressName='IPAll' and PropertyType=1 and ProtocolName='Tcp'"

    # there are two settings in a list: TcpPort and TcpDynamicPorts
    foreach ($setting in $settings)
    {
        if ($setting -ne $null)
        {
            # set the static TCP port and at the same time clear any dynamic ports
            if ($setting.PropertyName -eq "TcpPort")
            {
                $setting.SetStringValue($port)
            }
            elseif ($setting.PropertyName -eq "TcpDynamicPorts")
            {
                $setting.SetStringValue("")
            }
        }
    }
}

現在,這個函數的使用方式如下:

SetPort "SQLInstance" 1433

該腳本應提升運行,即以管理員身份執行

積分轉到這篇博文這為我指明了正確的方向。

相關內容