Setting SQL Alias with PowerShell
PROBLEM: The SQL Servers instances I manage have long cryptic names that are almost impossible to memorize and too many keystrokes to type; besides, I rather use my memory for other things. How can I set up aliases for all the SQL instances I manage in a quick an easy manner?
SOLUTION: The configuration of SQL aliases is saved in the registry under two locations. This first one is for 32bit clients HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer\Client\ConnectTo
And this second one is for 64bit clients HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo
PowerShell to the rescue! I wrote the Set-SQLAlias function that will take the SQL instance name, port number and alias I want to create. It will use this information to add an entry on the registry or modify an existing alias. I have added this function to my profile so it is always available. THIS FUNCTION MUST BE EXECUTED IN A POWERSHELL SESSION RUNNING UNDER ADMINSTRATOR PRIVILEGES”
Function Set-SqlAlias {
[Cmdletbinding()]
param ( [parameter(Mandatory=$true)] [string] $SqlInstanceName,
[parameter(Mandatory=$true)] [string] $Alias,
[parameter(Mandatory=$true)] [string] $Port,
[parameter(Mandatory=$false)] [string[]]$Client = @(32,64),
[parameter(Mandatory=$false)] $OverWrite = 0
)
BEGIN {
if($client -contains 64) {
$x64 = "HKLM:SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo"
if (!(Test-Path "$x64")) {
New-Item -Path "$x64" -Name "ConnectTo"
}
}
if ($client -contains 32) {
$x32 = "HKLM:SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo"
if (!(Test-Path "$x32")) {
New-Item -Path "$x32" -Name "ConnectTo"
}
}
}
PROCESS {
if ($OverWrite -ne 0) {
Get-Item -path "$x64" | Remove-ItemProperty -Name "$Alias" | Out-Null
Get-Item -path "$x32" | Remove-ItemProperty -Name "$Alias" | Out-Null
}
if (!(Get-Item -Path "$x32").GetValue("$Alias")) {
New-ItemProperty -Path "$x32" `
-Name "$Alias" `
-PropertyType String `
-Value $("DBMSSOCN,{0},{1}" -f "$SqlInstanceName", $Port) | Out-Null
}
if (!(Get-Item -Path "$x64").GetValue("$Alias")) {
New-ItemProperty -Path "$x64" `
-Name "$Alias" `
-PropertyType String `
-Value $("DBMSSOCN,{0},{1}" -f "$SqlInstanceName", $Port) | Out-Null
}
}
}
Thanks to my friend Rodney Starcher for helping me out with the PowerShell script.