This script can be used to query an SQL database

Script :

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=DBServerHostname;Database=master;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select * from DatabaseName"
$SqlCmd.Connection = $SqlConnection
$reader = $SqlCmd.ExecuteReader()
$Counter = $Reader.FieldCount
while ($Reader.Read()) {
	for ($i = 0; $i -lt $Counter; $i++) {
		@{ $Reader.GetName($i) = $Reader.GetValue($i); }
	}
}
$SqlConnection.Close()

Reference
SqlConnection Class
Represents an open connection to a SQL Server database. This class cannot be inherited.

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database. For all third-party SQL Server products, and other OLE DB-supported data sources, use OleDbConnection.
When you create an instance of SqlConnection, all properties are set to their initial values. For a list of these values, see the SqlConnection constructor.
See ConnectionString for a list of the keywords in a connection string.
If the SqlConnection goes out of scope, it won’t be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.

Query a SQL database

Leave a Reply

Your email address will not be published.