Last active
January 23, 2024 17:14
-
-
Save cmatskas/08411b916ab01e3f1439 to your computer and use it in GitHub Desktop.
PowershellSQLQuery.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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