Created
July 2, 2018 13:25
-
-
Save beancurd1/fc470913b62297fb70aee5ff9d6ebf2c to your computer and use it in GitHub Desktop.
Query Microsoft SQL Server with Invoke-Sqlcmd Powershell cmdlet
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
##### Simple Way, return an array or string (if 1 item is returned) ####### | |
$Date = @(Invoke-Sqlcmd -query "Select Convert(Varchar(11),Date,106) as Date From ValuationDate" -Server DBSERVER -Database DBNAME) | Select-Object -Expand Date | |
#####[ Another way to query MS SQL, it returns a Dataset Object ]##### | |
$SQLServer = "DBSERVER_NAME" #use Server\Instance for named SQL instances! | |
$SQLDBName = "DATABASE_NAME" | |
$SqlQuery = "Select something From A_TABLE" | |
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection | |
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True" | |
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand | |
$SqlCmd.CommandText = $SqlQuery | |
$SqlCmd.Connection = $SqlConnection | |
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$SqlAdapter.SelectCommand = $SqlCmd | |
$DataSet = New-Object System.Data.DataSet | |
$SqlAdapter.Fill($DataSet) | |
$SqlConnection.Close() | |
clear | |
$DataSet.Tables[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment