concept SQL Server in category powershell

appears as: SQL Server, SQL Server
Learn PowerShell Scripting in a Month of Lunches

This is an excerpt from Manning's book Learn PowerShell Scripting in a Month of Lunches.

Later in this book, we’re going to teach you how to use SQL Server as a data store for PowerShell scripts. We can’t express how important a skill this is in today’s business world. If we could physically print this paragraph in bold, italicized, blinking text at 64 point, we’d do it. Watching administrators struggle to use Excel as a “database” by digging into its deprecated, decade-old, COM-based automation model makes us sad. Excel isn’t a database, and it isn’t your friend when it comes to data storage.

We won’t run you through deep administration tasks on SQL Server Express; Don has a great book, Learn SQL Server Administration in a Month of Lunches (Manning, 2014, www.manning.com/books/learn-sql-server-administration-in-a-month-of-lunches), if SQL Server is an all-new tool for you. But we’d like to get you through a basic setup. We’ll refer you to the Microsoft tutorial “Getting Started with the Database Engine” at http://mng.bz/u04t, which will show you how to download the SQL Server Management Studio (also recommended) and get it up and running.

Listing 26.4. Adding a command to export data to SQL Server
function Export-DiskInfoToSQL { [CmdletBinding()] param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] [object[]]$DiskInfo ) BEGIN { New-DiskInfoSQLTable $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = $DiskInfoSqlConnection $conn.Open() $cmd = New-Object System.Data.SqlClient.SqlCommand $cmd.Connection = $conn } PROCESS { ForEach ($object in $DiskInfo) { if ($object.size -eq $null) { $size = 0 } else { $size = $object.size } if ($object.freespace -eq $null) { $freespace = 0 } else { $freespace = $object.freespace } $sql = @" INSERT INTO DiskInfo (ComputerName, DiskSize,DriveType,FreeSpace,DriveID,DateAdded) VALUES('$($object.ComputerName)', $size, $($object.DriveType), $freespace, '$($object.Drive)', '$(Get-Date)') "@ $cmd.CommandText = $sql Write-Verbose "EXECUTING QUERY `n $sql" $cmd.ExecuteNonQuery() | Out-Null } #ForEach } #PROCESS END { $conn.Close() } }

We don’t want this chapter to get bogged down in teaching you about SQL Server or how to manage it. If you need some place to start, you might take a look at Don’s Learn SQL Server Administration in a Month of Lunches (Manning, 2014, www.manning.com/books/learn-sql-server-administration-in-a-month-of-lunches). Manning has a live video “book” titled SQL in Motion by Ben Brumm (2017, www.manning.com/livevideo/sql-in-motion). And if you’re a Plural sight subscriber (www.pluralsight.com), you’ll find many courses on the subject.

Here are some of the advantages of using SQL Server (or, honestly, any relational database management system—if you prefer one over SQL Server, most of what’s in this chapter will still work fine for you):

PowerShell Deep Dives

This is an excerpt from Manning's book PowerShell Deep Dives.

For the SharePoint-to-SQL-Server authentication test you want to run the PowerShell script shown in listing 2, which has the logon-type codes and values incorporated, against the SQL Server and look for the Active Directory service accounts that are used by SharePoint on the web frontends. As with the previous script, this script is parameterized for the computer name and the number of records to return. This script uses a Switch statement in a hash table to return a meaningful name for the logon-type code, which indicates the type of logon session that took place when a user logged onto the server. It then customizes the column header names in a hash table, and finally sorts by server name in ascending order and then by time in descending order.

This chapter is written for the DBA who needs an efficient way to get information from or manage SQL Servers in their environment with just a few commands by using native PowerShell methods. When you’re looking at the options for managing or getting information from a SQL Server by using PowerShell your choice is driven by a few scenarios. One use case might be to find out how many databases are in the instances you maintain while using the simplest way to reference these instances. Another might be to find out whether a certain object exists in a Software as a Service (SaaS) environment with thousands of databases and multiple servers while upgrading in a phased upgrade methodology. You may want to know which database has the object so you don’t attempt to upgrade that database in the second wave and find that the object exists. When faced with these or other scenarios you can quickly accomplish your goal with part PowerShell methods and part SQL Server provider.

You have a few options for managing SQL Server using PowerShell. You can use straight Shared Management Objects (SMOs) by loading the SMOs individually or by using the SQL Server provider. This chapter discusses the SQL Server provider that was released with SQL Server 2008/2008 R2. The provider for SQL 2008/R2 is implemented as a Windows PowerShell snap-in (PSSnapin) and is implemented as a module in SQL Server 2012. The provider for SQL Server 2012 has a few more cmdlets and more properties and methods on the SMOs, but the functionality is the same. I’ll start by introducing you to the SQL Server provider and then I’ll show you practical ways to use the provider to get at SQL Server information using PowerShell cmdlets.

Listing 3. Displaying a list of database names from SQL Server
Prepare-SQLProvider cd SQLSERVER:\SQL\localhost\default cd Databases Get-Childitem | Select Name

In this chapter you’ve seen how to get the SQL Server PowerShell provider for 2008/R2 and how to add it to your PowerShell session. The SQL Server provider for PowerShell is provided as a snap-in and is loaded with the Add-PSSnapin command; you access the structure of SQL Server using a path structure. You can add the provider to any Windows machine by downloading the PowerShell objects in the SQL Server Feature Packs.

Whether you’re retrieving objects individually or detecting their existence a path structure provides a powerful way to use PowerShell and SQL Server together. This is just the tip of the iceberg when it comes to what you can do with the provider and how it all works, but I hope you caught the vision of where you can take it.

Chapter 25 discusses SMO and how to use objects in SQL Server with SMO; that chapter is a great companion to what you learned here. SQL Server 2012 wasn’t covered in this chapter, but the concepts apply to the SQL Server 2012 provider; it’s just loaded as a module (SQLPS) instead of a snap-in. Now, go execute some PowerShell!

About the author

Ben Miller is a database architect for HealthEquity, Inc. in Draper, Utah, the largest US Health Savings Account (HSA) trust organization. He is a SQL Server MVP and an MCM: SQL Server 2008. He has been in the industry for over 20 years and has focused on SQL Server and automation for the past 12 years. He has held various positions at companies like Microsoft and the LDS Church. He regularly speaks on SQL Server and PowerShell topics, and he is president of the Utah County, Utah SQL Server User Group. Ben lives in Lehi, Utah, with his beautiful wife and two children.

PowerShell in Practice

This is an excerpt from Manning's book PowerShell in Practice.

Have you ever wanted a consistent method of working with multiple data stores such as the filesystem, Active Directory, SQL Server, IIS, and the Windows Registry? PowerShell can deliver a large part of that vision through the use of providers.

SQL Server Management Objects (SMO to its friends) is a .NET management interface introduced with SQL Server 2005. It’s a hierarchical object model in that servers contain databases, which contain tables, which contain columns, and so on. SMO can be used to programmatically manage SQL Server 2000 and later. We can use it in PowerShell, but there’s one slight snag in that it’s not loaded into PowerShell by default.

We overcome this by loading the SQL Server client tools on the machine we’re going to use for administration. If you load the latest version of the tools (SQL Server 2008), you should be able to administer SQL Server 2000, 2005, and 2008 with them. The SMO .NET assemblies are installed with the tools and we can then load them into PowerShell, as in listing 14.1.

Listing 14.1. Load SQL 2005 SMO assemblies
$null = [reflection.assembly]:: LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") [void][reflection.assembly]:: LoadWithPartialName("Microsoft.SqlServer.SmoEnum") [reflection.assembly]:: LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null

With SQL Server 2005, we have three assemblies to load as shown. They all use the LoadWithPartialName static method to perform the load. The full name of the assembly could be discovered and used instead if preferred. Three different techniques are used to suppress the messages produced by loading the assemblies. We can use $null to absorb the messages; we can use the .NET [void], which serves the same purpose (but might seem too developer-like), or we can pipe the results to Out-Null. Pick whichever you prefer, as they work equally well. In PowerShell v2, I’d use Add-Type to load the assembly.

We could put these three lines in each script that uses SMO, but it’s more efficient to execute them as part of the PowerShell profile or in a specific script that we dot-source to perform the load. A similar technique can be used with SQL Server 2008, but it’s more complicated, as we’ll see.

SQL Server is useless without a network. Just try pulling the network cable and see how long it is before your users start shouting. Communication obviously depends on the networking components in the Windows OS. It also depends on SQL Server’s network configuration. There isn’t much to configure. There are the protocols to use, together with the IP addresses and ports SQL Server is listening on.