Accessing SQLServer Database

by Oct 28, 2014

All Versions, SQL Server

You are running an SQL Server? Then here is a PowerShell script template you could use to run an SQL query and retrieve the data. Simply make sure you fill in the correct user details, server address, and SQL statement:

$Database                       = 'Name_Of_SQLDatabase'
$Server                         = '192.168.100.200'
$UserName                         = 'DatabaseUserName'
$Password                       = 'SecretPassword'

$SqlQuery                       = 'Select * FROM TestTable'

# Accessing Data Base
$SqlConnection                  = New-Object -TypeName System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password"
$SqlCmd                         = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText             = $SqlQuery
$SqlCmd.Connection              = $SqlConnection
$SqlAdapter                     = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand       = $SqlCmd
$set                            = New-Object data.dataset

# Filling Dataset
$SqlAdapter.Fill($set)

# Consuming Data
$Path = "$env:temp\report.hta"
$set.Tables[0] | ConvertTo-Html | Out-File -FilePath $Path

Invoke-Item -Path $Path  

Twitter This Tip! ReTweet this Tip!