tags:

views:

331

answers:

2

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

+1  A: 
$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
Gordon Bell
+1  A: 

If you are using SQL Server 2008 you should consider using the cmdlets that are avaliable to PowerShell such as Invoke-SqlCmd that can be used to execute querries 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 avaliable to your session.

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100

Once they are avaliable 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

Alan