Automate turning named-pipes and tcp\\ip on

2019-07-06 14:36发布

问题:

I am working on an install of a new product that requires modifications to SQL Server.

Specifically, enable tcp/ip and turning on named pipes. I know how to do it manually. What i want is a way to automate this for a new customer though SQL or with C# code.

I would love any suggestions for the right direction.

回答1:

You can use C# and Server Management Objects (SMO) to do it. The classes you need are in the Microsoft.SqlServer.Smo and Microsoft.SqlServer.WmiManagement libraries.

Here's a Powershell snippet I've used that uses the same objects. Hopefully, it will point you down the right path.

$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