Query a SQL database with Powershell

This script can be used to query an SQL database

$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()
 
Cheers