Monday, November 24, 2014

Accessing SQL Server via SMO using PowerShell - A quick workout

In order to understand SQL Server the surest way is to get to understand the SQL Server Management Objects known by its acronym 'SMO'. You can programmatically access and manage SQL Servers with this object model.

I have described with code listing as to how you may access Azure SQL Database in my comprehensive Azure SQL Database related book.
"A step-by-step procedure to connect to SQL Azure using SMO" is described on page 119, Chapter 3 of this book.
Microsoft SQL Azure: Enterprise Application Development, Packt Publishing,  Dec 2010.

SMO is the foundation using which the SSMS was built. The name space for the SMO is Microsoft.SqlServer.SMO.

In a previous post, I showed you how to run PowerShell in SQL Server Management Studio. Here is a quick screen shot to refresh your memory.

As you can imagine the SMO object model is quite large and starts off with the Server at the top. This image shows only a part of this object model.

You should be able to access the complete model at this link:

In order to access SMO using PowerShell you need to load the assembly as shown in the next image.

With the following you can get all the members as shown.

Once you do that you can access the top-level object, the Server.

SMO is object based and hierarchical. You define the SQL Server as a new object using the next listing where "servername" is your computer or the server and instance name is the SQL Server instance. In the present listing it is "Hodentek\RegencyPark"
PS C:\Users\Jayaram> $sqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") "Hodentek8\RegencyPark"

Since you defined  the server, you can find its version as shown in the following listing:
PS C:\Users\Jayaram> $sqlServer.version
Major  Minor  Build  Revision
-----  -----  -----  --------
11     0      2218   -1

The next two lines of code finds the status of the server as well as the root directory of the instance. 
PS C:\Users\Jayaram> $sqlserver.status
PS C:\Users\Jayaram> $sqlserver.RootDirectory
c:\Program Files\Microsoft SQL Server\MSSQL11.REGENCYPARK\MSSQL
Accessing the databases:

Databases are also objects and you need declare a variable for them as shown here:
PS C:\Users\Jayaram> $sqlDatabase=$sqlServer.Databases
The above declaration will not display a response but you have indeed declared the variable $sqlDatabase
Since there are more than one database, you need to get information from this collection as shown in the next listing:
PS C:\Users\Jayaram> foreach($sqlDatabse in $sqlServer.Databases){$}

These are the databases in my SQL Server Instance named RegencyPark.

In a future post we will see how to query database and other tasks