Quantcast
Channel: SQL Archives - SQL Authority with Pinal Dave
Viewing all articles
Browse latest Browse all 594

PowerShell – Querying SQL Server From Command Line

$
0
0

PowerShell is quite an interesting capability that is added as part of Windows. I wonder how many of us really appreciate the power of this tool being out of the box. The more I see it being used in customer locations, the more I get intrigued by what it can do. Let us learn about Querying SQL Server From Command Line via powershell.

In a recent consulting assignment, I saw the development team use interesting methodology to do their code deployment. They were using PowerShell scripts to actually do the code deployment on various servers. While they were moving from one environment to another like from Dev to Test to Integration of Production, they were changing just a single parameter.

The whole thing got me interested. I asked how they were able to get this achieved. What happens to the environment specific variables, values? The Dev guy turns around and told me – “Pinal, everything is in safe hands of SQL Server”. As I stared at him with amusement, he opened up an Config Database and started showing how the trivial (though critical) values are stored in the database. They were using PowerShell to actually query these values and use it effectively in their script.

Watching the script I saw them using: Invoke-SqlCmd. This is when I started to see how powerful PowerShell scripts can be made using some out-of-box tools even without installing SQL Server on a box. I created a small script below to show how we can query a DMV and the output is put in the window.

Invoke-SqlCmd -Query "Select * from sys.databases" -ServerInstance "." 

PowerShell - Querying SQL Server From Command Line QueryDB-PowerShell-01

As you can see, the output is like what you would see inside an SSMS but in a property and value mode. This is repeated for all the databases inside the test instance of mine.

Have you ever had an opportunity to build such scripts in production environments? I would love to learn from you on how you maximized the use of Invoke-SqlCmd in your environment. Please use the comments below to let me know. Is this something new for you?

Reference: Pinal Dave (http://blog.SQLAuthority.com)

The post PowerShell – Querying SQL Server From Command Line appeared first on Journey to SQL Authority with Pinal Dave.


Viewing all articles
Browse latest Browse all 594

Trending Articles