Powershell SQL选择输出到变量
我正在调用一个函数来查询SQL表。我只需要一个单元格的结果。 我无法从函数中将单元格数据成功检索到变量中 例如,如果我有一个包含以下内容的表:Powershell SQL选择输出到变量,sql,powershell,Sql,Powershell,我正在调用一个函数来查询SQL表。我只需要一个单元格的结果。 我无法从函数中将单元格数据成功检索到变量中 例如,如果我有一个包含以下内容的表: FeedID Name Address 15 Bill Jones 我需要将FeedID值'15'捕获到一个变量中。 我的SQL语句只捕获FeedID,但我不知道如何提取值 以下是我到目前为止的情况: function Invoke-SQL { param( [string] $d
FeedID Name Address
15 Bill Jones
我需要将FeedID值'15'捕获到一个变量中。
我的SQL语句只捕获FeedID,但我不知道如何提取值
以下是我到目前为止的情况:
function Invoke-SQL {
param(
[string] $dataSource = "10.0.100.1",
[string] $database = "Database123",
[string] $sqlCommand = $("SELECT [FeedID] FROM [dbo].[FeedList] WHERE [FeedFileName] = 'filename.txt'")
)
$connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
write-output $adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
}
$FeedID = Invoke-SQL
$FeedID
看起来$FeedID(您放入SQL输出的变量)应该有一个FeedID属性(来自返回的单行)
试试这个:
$FeedID.FeedID
或者,如果要查找简单的返回值,而不是用于以后处理的表,则可以使用以下代码
[string] $Server= "10.0.100.1",
[string] $Database = "Database123",
[string] $SQLQuery= $("SELECT [FeedID] FROM [dbo].[FeedList] WHERE [FeedFileName] = 'filename.txt'")
function GenericSqlQuery ($Server, $Database, $SQLQuery) {
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
while ($Reader.Read()) {
$Reader.GetValue(0)
}
$Connection.Close()
}
执行后,
$FeedID
的内容是什么?FeedID和编号。很好用!谢谢。这只是因为$1是未定义的,在$Reader.GetValue($1)中使用时被视为0。这比公认的答案简单得多,也更惯用。