我在调用TSQL查询结果的PowerShell脚本时遇到问题。我希望将SQL查询的结果作为单个值而不是数据集分配给$ Output变量。从我的PowerShell脚本下面,$ Output变量返回...
$Output
Column1
--------
100
当我需要结果返回单个值时,如下所示......
$Output
100
以下是我正在使用的PowerShell脚本:
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCmd
$Dataset = new-object System.Data.Dataset
write-output $DataAdapter.Fill($Dataset) | Out-Null
$Output = $DataSet.Tables
$Output
非常感谢任何帮助!
答案 0 :(得分:3)
这是你正在寻找的吗?
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
$Output = $SqlCmd.ExecuteScalar()
$Output
$SqlCmd.ExecuteScalar()
返回标量值。
希望它有所帮助。