{"id":32,"date":"2013-10-30T00:00:00","date_gmt":"2013-01-01T00:00:00","guid":{"rendered":"https:\/\/www.sqlhammer.com\/blog\/t-sql-command-line-options-part-3-ps-w-net"},"modified":"2026-03-18T21:50:19","modified_gmt":"2026-03-18T21:50:19","slug":"t-sql-command-line-options-part-3-ps-w-net","status":"publish","type":"post","link":"https:\/\/sqlhammer.com\/index.php\/2013\/10\/30\/t-sql-command-line-options-part-3-ps-w-net\/","title":{"rendered":"T-SQL Command Line Options &#8211; Part 3 &#8211; PS w\/ .NET"},"content":{"rendered":"<h2>Powershell and .NET Objects<\/h2>\n<p>Now that we\u2019ve covered SQLCMD.exe with the command prompt I\u2019d like to dive into the present and future of Windows command line, Powershell. One of the great things about Powershell is that for every task there are always multiple ways to tackle it. In this blog series I will be covering three different methods of establishing a SQL Server connection and executing a query. Of those three ways there are different situations where you might be forced to pick one over the other but we\u2019ll get into that as I cover each.<\/p>\n<h2>Why this method?<\/h2>\n<p>I think all DBAs will agree that, given the option between command prompt and Powershell, you should always use Powershell. Powershell has all of the capabilities as command prompt plus so much more. So, now that you\u2019ve chosen Powershell and verified that you have it installed; why would we use .NET?<\/p>\n<p>Powershell exposes the entire .NET framework to the script writer so, naturally, you can use the exact same .NET objects to build your SQL connection, execute queries, and retrieve the results. There are, however, other methods of using Powershell to interact with SQL Server, as mentioned above.<\/p>\n<p>Recently I needed to have a T-SQL script file executed on an entire active-active topology of SQL Server. The scripts were related to peer-to-peer replication, I could not predict how the code would change by the developers in the future, it had to be run outside of the individual node\u2019s SSDT dacpac deployments, and it had to snap into their continuous integration seamlessly. They already had a requirement to run their deployment agents on Server 2008 R2 or above so I could assume I had access to Powershell 2.0 but couldn\u2019t count on the deployment agent having any of the SQL modules installed. So, in an effort to write re-usable code that was flexible and didn\u2019t impose any new requirements on the change management team, I chose to use .NET. This method does not require anything that is not native to Windows Server 2008 R2 or higher.<\/p>\n<h2>How to use it<\/h2>\n<p>First off, I highly recommend using the Windows Powershell ISE which comes prepackaged with Windows 7 and 8. If you are running Windows Server or just don\u2019t want to use the ISE then the normal Powershell console will work just fine as well.<\/p>\n<p>We are going to start off by establishing our variables. The timeout settings seen below are optional but I like to include them in case the defaults need adjustment at a future date.<\/p>\n<pre><code class=\"language-\">$ConnectionTimeOutInSeconds = 30;\n$CommandTimeOutInSeconds = 30;\n$server = 'localhost\\SQL2008R2';\n$database = 'master';<\/code><\/pre>\n<p>Next we will; instantiate the SQLConnection object, set the connection string, and open the connection.<\/p>\n<pre><code class=\"language-\"># establish connection\n$Conn=New-Object System.Data.SQLClient.SQLConnection \"Server=$server;Database=$database;Trusted_Connection=Yes;Connection Timeout=$ConnectionTimeOutInSeconds;\";\n$Conn.Open();<\/code><\/pre>\n<p>We will then instantiate the SqlCommand object and set the command timeout.<\/p>\n<pre><code class=\"language-\"># instantiate command object\n$DataCmd = New-Object System.Data.SqlClient.SqlCommand;\n$DataCmd.CommandTimeout = $CommandTimeOutInSeconds;<\/code><\/pre>\n<p>This next snippet will extract the T-SQL text from a file and load it into the $MyQuery variable<\/p>\n<pre><code class=\"language-\"># extract T-SQL\n$sqlFile = 'C:\\Fake_Test_File.sql';\n$MyQuery = (get-content ($sqlFile));<\/code><\/pre>\n<p>Alternatively, you may also hard code the query like so.<\/p>\n<pre><code class=\"language-\">$MyQuery = \"SELECT <code>'Don<\/code>'t forget to subscribe to the SQLHammer.com RSS feed.<code>'\";<\/code><\/pre>\n<p>Next we will set the command object\u2019s connection property and execute. This first example is for a non-query such as DML commands.<\/p>\n<pre><code class=\"language-\"># associate command to connection\n$DataCmd.Connection = $Conn;\n<h1>execute script<\/h1>\n$DataCmd.ExecuteNonQuery();<\/code><\/pre>\n<p>This second example is to execute a query and print the results to the console.<\/p>\n<pre><code class=\"language-\">$reader = $Conn.ExecuteReader(\"SELECT Name, CostRate FROM Production.Location\")\nwhile ($reader.Read())\n{\n   $name = $reader.GetValue(0);\n   $cRate = $reader.GetValue(1);\n   Write-Host $name,\"(\",$cRate,\")\"\n}<\/code><\/pre>\n<p>Finally, we collect the garbage.<\/p>\n<pre><code class=\"language-\"># clean up\n$Conn.Close();\n$Conn.Dispose();<\/code><\/pre>\n<h3>Full script \u2013 non-query<\/h3>\n<pre><code class=\"language-\">##############################################\n<h1>Set Variables<\/h1>\n##############################################\n\n<p>$ConnectionTimeOutInSeconds = 30;\n$CommandTimeOutInSeconds = 30;\n$server = 'localhost\\SQL2008R2';\n$database = 'master';<\/p>\n\n<p>##############################################\n<h1>Execute scripts<\/h1>\n##############################################<\/p>\n\n<h1>establish connection<\/h1>\n$Conn=New-Object System.Data.SQLClient.SQLConnection \"Server=$server;Database=$database;Trusted_Connection=Yes;Connection Timeout=$ConnectionTimeOutInSeconds;\";\n$Conn.Open();\n\n<h1>instantiate command object<\/h1>\n$DataCmd = New-Object System.Data.SqlClient.SqlCommand;\n$DataCmd.CommandTimeout = $CommandTimeOutInSeconds;\n\n<h1>extract T-SQL<\/h1>\n$sqlFile = 'C:\\Fake_Test_File.sql';\n$MyQuery = (get-content ($sqlFile));\n\n<h1>associate command to command text<\/h1>\n$DataCmd.CommandText = $MyQuery;\n\n<h1>associate command to connection<\/h1>\n$DataCmd.Connection = $Conn;\n\n<h1>execute script<\/h1>\n$DataCmd.ExecuteNonQuery();\n\n<h1>clean up<\/h1>\n$Conn.Close();\n$Conn.Dispose();<\/code><\/pre>\n<h3>Full script \u2013 query read<\/h3>\n<pre><code class=\"language-\">##############################################\n<h1>Set Variables<\/h1>\n##############################################\n\n<p>$ConnectionTimeOutInSeconds = 30;\n$CommandTimeOutInSeconds = 30;\n$server = 'localhost\\SQL2008R2';\n$database = 'master';<\/p>\n\n<p>##############################################\n<h1>Execute scripts<\/h1>\n##############################################<\/p>\n\n<h1>establish connection<\/h1>\n$Conn=New-Object System.Data.SQLClient.SQLConnection \"Server=$server;Database=$database;Trusted_Connection=Yes;Connection Timeout=$ConnectionTimeOutInSeconds;\";\n$Conn.Open();\n\n<h1>instantiate command object<\/h1>\n$DataCmd = New-Object System.Data.SqlClient.SqlCommand;\n$DataCmd.CommandTimeout = $CommandTimeOutInSeconds;\n\n<h1>extract T-SQL<\/h1>\n$sqlFile = 'C:\\Fake_Test_File.sql';\n$MyQuery = (get-content ($sqlFile));\n\n<h1>associate command to command text<\/h1>\n$MyQuery = \"SELECT <\/code>'Don<code>'t forget to subscribe to the SQLHammer.com RSS feed.<\/code>'\";\n\n<h1>associate command to connection<\/h1>\n$reader = $Conn.ExecuteReader($DataCmd.CommandText);\nwhile ($reader.Read())\n{\n   $name = $reader.GetValue(0);\n   $cRate = $reader.GetValue(1);\n   Write-Host $name,\"(\",$cRate,\")\"\n}\n\n<h1>clean up<\/h1>\n$Conn.Close();\n$Conn.Dispose();<\/code><\/pre>\n<h2>What\u2019s next?<\/h2>\n<p>In the next part of this blog series we will look into how to use the SQLPSX community built Powershell module.<\/p>\n<h2>Navigation<\/h2>\n<ul>\n<li><a href=\"http:\/\/www.sqlhammer.com\/blog\/t-sql-command-line-options-part-1\/\">Part 1 \u2013 Introduction<\/a><\/li>\n<\/ul>\n<ul>\n<li><a href=\"http:\/\/www.sqlhammer.com\/blog\/t-sql-command-line-options-part-2-sqlcmd-exe\/\">Part 2 \u2013 SQLCMD.exe using command prompt<\/a><\/li>\n<\/ul>\n<ul>\n<li>Part 3 \u2013 .NET objects using Powershell<\/li>\n<\/ul>\n<ul>\n<li>Part 4 \u2013 SQLPSX using Powershell (SQL Server 2000 and above)<\/li>\n<\/ul>\n<ul>\n<li>Part 5 \u2013 SQLPS using Powershell (SQL Server 2012 \/ 2014)<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Powershell and .NET Objects Now that we\u2019ve covered SQLCMD.exe with the command prompt I\u2019d like to dive into the present and future of Windows command line, Powershell. One of the great things about Powershell is that for every task there are always multiple ways to tackle it. In this blog series I will be covering [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-32","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/posts\/32","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/comments?post=32"}],"version-history":[{"count":1,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/posts\/32\/revisions"}],"predecessor-version":[{"id":295,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/posts\/32\/revisions\/295"}],"wp:attachment":[{"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/media?parent=32"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/categories?post=32"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sqlhammer.com\/index.php\/wp-json\/wp\/v2\/tags?post=32"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}