PoshCode Logo PowerShell Code Repository

Invoke-SqlCmd2 by Chad Miller 22 months ago (modification of post by Chad Miller view diff)
View followups from Chad Miller and Jaans | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1791"></script>download | new post

Modeled after SQL Server 2008 Invoke-Sqlcmd, but fixes bug in QueryTimeout. Fixed minor issue closing connection.

  1. function Invoke-Sqlcmd2
  2. {
  3.     param(
  4.     [string]$ServerInstance,
  5.     [string]$Database,
  6.     [string]$Query,
  7.     [Int32]$QueryTimeout=30
  8.     )
  9.  
  10.     $conn=new-object System.Data.SqlClient.SQLConnection
  11.     $conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $ServerInstance,$Database
  12.     $conn.Open()
  13.     $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
  14.     $cmd.CommandTimeout=$QueryTimeout
  15.     $ds=New-Object system.Data.DataSet
  16.     $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
  17.     [void]$da.fill($ds)
  18.     $conn.Close()
  19.     $ds.Tables[0]
  20.  
  21. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me