Earlier in this blog, I have written a number of posts by using PowerShell. The more you play around with this scripting language more are the hidden gems that come out. Personally for me, everyday is like a new learning that needs to be discovered working with SQL Server and PowerShell. One of the posts that I would like to recollect is: PowerShell – Querying SQL Server From Command Line
In the post mentioned above, I have mentioned one of the ways to query SQL Server from command line. This blog post is almost on similar lines in some way. But in this blog post, I will want to show the PowerShell commandlet for querying SQL Server.
Let me introduce you to Read-SQLTableData. When I saw this command, I went to my SQL Server box to check how this works. It was amazing to see the output from the PowerShell window. From SQL Server Management Studio, I went to a database, expanded Tables and selected a table with right click and “Start PowerShell”. In this example, I have taken the AdventureWorks, dbl.DatabaseLog table. Once on command prompt, fire the powershell commandlet as shown below:
This gets this simple from a query pattern point of view. It will display the complete table data on the console. From this is a console, we can always take the output to a .txt file if required.
One of the addendum to this is the ability to add few interesting parameters to the same query.
Read-SQLTableData -top 2 -OutputAs DataTable -ColumnName Event,Schema,Object,PostTime
Here in the above query, I have gone ahead to take the top 2 rows and have explicitly called out the column names of interest. The typical output of this would look like:
Interesting, isn’t it? I am sure once you start to play with PowerShell and the SQL commandlets, you will find interesting use cases of using the same. Feel free to let me know how you used this in your environments.
Reference: Pinal Dave (http://blog.sqlauthority.com)
First appeared on PowerShell – Reading Tables Data Using Script