Created
July 28, 2016 18:59
-
-
Save NoOneInParticular/6c41260df64c38c397309efdd092ac89 to your computer and use it in GitHub Desktop.
Run SQL Query with Powershell
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
# Setting up the connection string (suggest using a sql account vs Windows login) | |
$dataSource = "<server name>" | |
$user = "username" | |
$pwd = "password" | |
$database = "<database name>" | |
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;" | |
#Create the query and store it in a variable | |
$query = "SELECT [<ColumnName>] FROM [<DatabaseName>].[dbo].[<tablename>]" | |
#Opening the connection | |
$connection = New-Object System.Data.SqlClient.SqlConnection | |
$connection.ConnectionString = $connectionString | |
$connection.Open() | |
$command = $connection.CreateCommand() | |
#Run the query | |
$command.CommandText = $query | |
#Where to stick the results | |
$result = $command.ExecuteReader() | |
$JTtable = new-object System.Data.DataTable | |
$JTtable.Load($result) | |
# Formatting the results | |
$format = @{Expression={$_.Name};Label="Job Title";width=50} | |
# Getting the final output | |
return $JTtable | |
# Write-Host $JTtable (this can be used to write to other properties) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment