14

My goal is to assign the value of the results returned to a variable:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

The value returned should obviously be 'tempdb', so how can I assign this to a variable so this will work:

Write-output "Database is " $variablename

Desired output: Database is tempdb

2 Answers 2

18
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select name from sysdatabases where name = 'tempdb'"
$SqlCmd.Connection = $SqlConnection
$dbname = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Write-output "Database is " $dbname
Sign up to request clarification or add additional context in comments.

Comments

15

If you are using SQL Server 2008 you should consider using the cmdlets that are available to PowerShell such as Invoke-SqlCmd that can be used to execute queries against a SQL Server database. I've used these on a project to automate the process of applying patches to a database and recording what patches have been applied:

You will first need to use these two commands to make the SQL Server cmdlets available to your session.

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100

Once they are available you can invoke SQL commands as follows.

$x = invoke-sqlcmd -query "select name from sysdatabases where name = 'tempdb'"

The variable $x will hold the results of running the query.

Check out http://msdn.microsoft.com/en-us/library/cc281720.aspx for more details on using the SQL Server cmdlets

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.