Created
October 25, 2023 19:36
-
-
Save craeckor/697420b9a2827b674eb7117fc3ff490c to your computer and use it in GitHub Desktop.
Connect PowerShell script with MSSQL-Server
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
#-------------------------------------------------------------------------------------------------------------- | |
#-- Script to run query and get recordset | |
#-- Credits: SomTripathi --> https://gist.github.com/SomTripathi/651fd287250ad013720f | |
#-------------------------------------------------------------------------------------------------------------- | |
function Run-Query( [string]$InstanceName , [string]$DatabaseName, [string]$Query, [string]$Username, [string]$Password) | |
{ | |
$SQLInstance = $InstanceName | |
$DBName = $DatabaseName | |
$SQLQry = $Query | |
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection | |
$SqlConnection.ConnectionString = "Server = $SQLInstance; Database = $DBName; User ID = $Username; Password = $Password;" | |
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand | |
$SqlCmd.CommandText = $SQLQry | |
$SqlCmd.Connection = $SqlConnection | |
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$SqlAdapter.SelectCommand = $SqlCmd | |
$DataSet = New-Object System.Data.DataSet | |
$SqlAdapter.Fill($DataSet) | |
$SqlConnection.Close() | |
#--Show data in table --# | |
$DataSet.Tables[0] | |
} | |
#--Select everything from a table in a database with login credentials--# | |
$result = Run-Query -InstanceName "server\instance" -DatabaseName "MyDatabase" -Query "SELECT * FROM MyTable" -Username "myusername" -Password "mypassword" | |
#-------------------------------------------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment