As an alternative to ExecuteReader below, it is also possible to run insert/update statements using the ExecuteNonQuery method because they do not return rowsets that need to be fetched and processed.
# Mike Burr
# March 2013
# Demonstration Script to perform basic Microsoft SQL Server query using PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("System.Data.SqlClient")
# Define the connection string for the database connection. Typically the
# account running the script or the application pool identity
# has appropriate access to the database allowing integrated security
# to be used. In limited cases, it may be necessary to define a username and
# password in the connection string
$ConnectionString = "Data Source=localhost;Database=MyTestDB;Integrated Security=True;"
$conn = new-object "System.Data.SqlClient.SqlConnection" $ConnectionString
Try {
$conn.Open()
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT DISTINCT a FROM Test where a = @a"
$reader = $cmd.ExecuteReader()
while ($reader.Read()) {
$value = $reader["a"]
}
} Finally {
$conn.Close();
} -->See Also:
How to Query a MySql Database using Windows PowerShell