Sql – Exec sproc from Powershell

execpowershellpowershell-2.0sqlstored-procedures

I would like to execute a stored procedure from Powershell (v2) against a SQL Server 2008 database. Coming from using C# as my primary language, I'm doing it in that fashion. For example, when I need to run a sproc that doesn't return results, here is what I'm doing now:

$con = new-object System.Data.SqlClient.SqlConnection($connectionString)
$cmd = new-object System.Data.SqlClient.SqlCommand("exec MySproc", $con)
$con.Open()
$cmd.ExecuteNonQuery()
$cn.Close()

While perhaps TMTOWTDI, I'd like to know the best way.

I should mention that I'm already familiar with T-SQL and the System.Data namespace. This is really a question about Powershell.

Best Answer

For straight PowerShell I would go with code like you and Andomar have written. However if you are using the PowerShell Community Extensions there are some cmdlets for working with ADO e.g.:

$conn = 'Data Source=.\SQLEXPRESS;Initial Catalog=pubs;Integrated Security=SSPI'
$ds = Invoke-AdoCommand -ProviderName SqlClient -ConnectionString $conn `
          -CommandText 'Select * from Authors' -AsDataSet
$ds.Tables


au_id    : 172-32-1176
au_lname : White
au_fname : Johnson
phone    : 408 496-7223
address  : 10932 Bigge Rd.
city     : Menlo Park
state    : CA
zip      : 94025
contract : True

...