Skip to content

Instantly share code, notes, and snippets.

@cmatskas
Last active January 23, 2024 17:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmatskas/08411b916ab01e3f1439 to your computer and use it in GitHub Desktop.
Save cmatskas/08411b916ab01e3f1439 to your computer and use it in GitHub Desktop.
PowershellSQLQuery.ps1
[string] $Server= ".\SQLEXPRESS2014"
[string] $Database = "MyDatabase"
[string] $UserSqlQuery= $("SELECT * FROM [dbo].[User]")
# declaration not necessary, but good practice
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
return $Datatable
}
#validate we got data
Write-Host ("The table contains: " + $resultsDataTable.Rows.Count + " rows")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment