Connecting to SQL Server

This category page is part of a series of Professional PowerShell SMO Recipes. You can find an index of all recipes on the main SMO Recipes page, and if you want to learn more about each recipe and see some sample screenshots, click on its category page.

These scripts were created and tested on Windows 8.1 with PowerShell v4 and SQL Server 2014, though most recipes should work with earlier versions of SQL Server. PowerShell v3 and above is required for many of the recipes. If you have a recipe request, leave a comment and I'll see what I can do. This cookbook will be continuously built, as I work more with SMO.

Recipe Categories

Connecting to SQL Server

Connect / Test Connection / Disconnect from SQL Server

The follow recipe will create the server instance, attempt a connection, then disconnect. In my formally-written PowerShell scripts, I’ll generally place the Connect() in PROCESS {} and Disconnect() in the END {}.

Using Windows Authentication

Using SQL Login Authentication

Connect to SQL Server on a specific port

SQL Server’s default port is port 1433, though named instances can reside on different ports. While SMO can usually automatically find the instance’s port, sometimes the port must be specified. Here’s the syntax.

Connecting to SQL Server Configuration Manager (SqlWmiManagement)

See “Programmatically change SQL Server startup parameters” under Administration for more details.

Connecting to a SQL Server Central Management Server

Most code examples show how to connect using a manually specified SqlConnectionObject but did you know you can get the SqlConnectionObject from within SMO’s ConnectionContext?

Is SMO installed on the local computer?

If you don’t have SQL Server or SQL Server Management studio installed on a computer, you will need to manually install SMO to use these scripts. The links provided below will lead you to Microsoft’s SQL Server 2014 Feature Pack page. Click Download, and once the pop-up has appeared, search for your architecture’s SharedManagementObjects.msi file, download and install.

Want to see more? You can find an index of all recipes on SMO Recipes Index Page page or click on any specific category at the top of this page.

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, holds a master's degree in Systems Engineering and is coauthor of Learn dbatools in a Month of Lunches. Chrissy is certified in SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

One comment on “Connecting to SQL Server
  1. Nav says:

    Thanks for this article, helped me out heaps!

Leave a Reply

Your email address will not be published. Required fields are marked *