1.Create a connection
2.Create your command (the T-SQL that will be executed)
3.Create your data adapter (if you want to retrieve data)
4.Create your dataset (the adapter fills this object)
Create a Connection
You simply create an object of System.Data.SqlClient.SqlConnection and pass the connection string that will be used to connect to the given SQL Server instance…don’t forget to open it.
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = “Server=localhost\sql12;Integrated Security=true;Initial Catalog=master”
$sqlConn.Open()
Create Your Command
You have a few options here because the SqlConnection actually contains a method that you can use to create your command object, or you can create a separate object all together. I have seen both options used so it is for the most part a preference.
$sqlcmd = $sqlConn.CreateCommand()
<# or #>
$sqlcmd = New-Object System.Data.SqlClient.SqlCommand
$sqlcmd.Connection = $sqlConn
$query = “SELECT name, database_id FROM sys.databases”
$sqlcmd.CommandText = $query
Create Your Data Adapter
By definition, this object “represents a set of data commands and a database connection that are used to fill the DataSet”. You create the SqlDataAdapter and pass it to the previous command object created, $sqlcmd.
$adp = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcmd
Create Your DataSet (and fill it)
This object will be the type of System.Data.DataSet and as defined is simply “an in-memory cache of data”. Which this is something to take note of that the query you are running has to be loaded into memory, so the larger the dataset the more memory needed.
$data = New-Object System.Data.DataSet
$adp.Fill($data) | Out-Null
Retrieving Your Data
After you do all that you are probably wondering how you output that data so you can see it? The data itself resides in a collection of tables within the Table property of your DataSet object. Now depending on the version of .NET you are working with you might actually need to specify the index of the collection (e.g. Tables[0]), but this is generally only required in older versions below .NET 4.0.
$data.Tables
<# or #>
$data.Tables[0]
For more information watch this video
https://youtu.be/P01_Zd11HX0