Last active
November 18, 2022 16:54
-
-
Save FrankSpierings/e69c92dce19759d738b68ef099856711 to your computer and use it in GitHub Desktop.
Very basic Powershell script to execute a SQL Query and show the result in a GridView
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
function Invoke-SQLCmd { | |
param( | |
[Parameter(Mandatory=$True)] | |
[string] $Server, | |
[Parameter(Mandatory=$True)] | |
[string] $Database, | |
[Parameter(Mandatory=$True)] | |
[string] $Query | |
); | |
$con = New-Object System.Data.SqlClient.SqlConnection($('Server = {0}; Database = {1}; Integrated Security = True;' -f $Server, $Database)); | |
$con.Open(); | |
$command = New-Object System.Data.SqlClient.SqlCommand($Query, $con); | |
$datatable = New-Object System.Data.DataTable; | |
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter; | |
$adapter.SelectCommand = $command; | |
$adapter.Fill($datatable) | Out-Null; | |
$con.Close(); | |
return $datatable; | |
} | |
$server = 'example.com'; | |
$db = 'master'; | |
$query = "SELECT * FROM sys.databases;"; | |
Invoke-SQLCmd -Server $server -Database $db -Query $query | Out-GridView; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment