我的目标是将返回结果的值赋给变量:
$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]
返回的值显然应该是'tempdb',所以如何将其赋值给变量以便这样做:
Write-output "Database is " $variablename
所需的输出:数据库是tempdb
答案 0 :(得分:16)
$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
答案 1 :(得分:15)
如果您使用的是SQL Server 2008,则应考虑使用PowerShell可用的cmdlet,例如Invoke-SqlCmd
,可用于对SQL Server数据库执行查询。我在项目中使用了这些来自动化将补丁应用到数据库并记录已应用补丁的过程:
首先,您需要使用这两个命令使SQL Server cmdlet可用于您的会话。
add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100
一旦可用,您可以按如下方式调用SQL命令。
$x = invoke-sqlcmd -query "select name from sysdatabases where name = 'tempdb'"
变量$x
将保存运行查询的结果。
有关使用SQL Server cmdlet的更多详细信息,请查看http://msdn.microsoft.com/en-us/library/cc281720.aspx