Published on

May 6, 2016

Querying SQL Server From Command Line via PowerShell

PowerShell is a powerful tool that comes pre-installed with Windows. However, many people are not aware of its capabilities and the potential it holds. In this article, we will explore how PowerShell can be used to query SQL Server from the command line.

During a recent consulting assignment, I came across a development team that was using PowerShell scripts for their code deployment. What intrigued me was their ability to seamlessly move from one environment to another (e.g., from Dev to Test to Integration or Production) by simply changing a single parameter. When I asked them how they achieved this, they confidently replied, “Pinal, everything is in the safe hands of SQL Server.”

Curious, I asked them to demonstrate how they managed environment-specific variables and values. To my surprise, they opened up a Config Database and showed me how critical values were stored in the database. They used PowerShell to query these values and effectively incorporate them into their scripts. One of the commands they used was Invoke-SqlCmd.

Let’s take a look at a simple script that queries a DMV (Dynamic Management View) and displays the output in the PowerShell window:

Invoke-SqlCmd -Query "SELECT * FROM sys.databases" -ServerInstance "."

The output of this command resembles what you would see in SQL Server Management Studio (SSMS), with properties and their corresponding values. This script can be repeated for all the databases within a given SQL Server instance.

Now, I’m curious to hear from you. Have you ever had the opportunity to build similar scripts in production environments? How have you maximized the use of Invoke-SqlCmd in your environment? Please share your experiences and insights in the comments below.

PowerShell is a versatile tool that can greatly enhance your SQL Server management and automation tasks. By leveraging its capabilities, you can streamline your workflows and improve efficiency. If you haven’t explored PowerShell’s potential yet, I encourage you to give it a try.

Stay tuned for more articles on SQL Server and PowerShell!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.