PowerShell: SQL queries, tables and output
$SQLSERVER = “myServer”
$DATABASE = “myDatabase”
$ID = 12345
$SqlQuery = “select colum1, ”
$SqlQuery = $SqlQuery + “column2 ”
$SqlQuery = $SqlQuery + “from tblSomething ”
$SqlQuery = $SqlQuery + “where ID = ” + $ID
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = “Server=$SQLSERVER;Database=$DATABASE;Integrated Security=SSPI;”
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$nSet = $SqlAdapter.Fill($DataSet)
$OutputTable = $DataSet.Tables[0]
$SqlConnection.Close();
To view the contents of the returned table object, try:
$OutputTable | ft -autosize
$OutputTable.rows[0].column1