Skip to content

Instantly share code, notes, and snippets.

@JohnRoos
Created July 14, 2015 09:22
Show Gist options
  • Save JohnRoos/cfa7132d75ae167fcace to your computer and use it in GitHub Desktop.
Save JohnRoos/cfa7132d75ae167fcace to your computer and use it in GitHub Desktop.
Simple select from database using PowerShell
# Variables for server, database and query
$server = 'localhost\sqlexpress'
$database = 'test'
$query = 'select top 10 * from fjutt'
# Set up the objects needed
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command
$dataset = New-Object -TypeName System.Data.DataSet
# Set the connection string (using single sign on) and open the connection
$connection.ConnectionString = "Server=$server;Database=$database;Trusted_Connection=True;"
$connection.Open()
# Create a command object and assign the query
$command = $connection.CreateCommand()
$command.CommandText = $query
# Fill the dataset and count the rows returned at the same time
$rowCount = $adapter.Fill($dataset)
# Since the dataset is populated we can now close the connection
$connection.Close()
# Return the results
$dataset.Tables.rows
# Print amount of rows to screen (optional)
Write-Host "Rows returned: $rowCount"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment