Skip to content

Instantly share code, notes, and snippets.

@beancurd1
Created July 2, 2018 13:25
Show Gist options
  • Save beancurd1/fc470913b62297fb70aee5ff9d6ebf2c to your computer and use it in GitHub Desktop.
Save beancurd1/fc470913b62297fb70aee5ff9d6ebf2c to your computer and use it in GitHub Desktop.
Query Microsoft SQL Server with Invoke-Sqlcmd Powershell cmdlet
##### 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