Powershell SQL SELECT输出到变量

前端之家收集整理的这篇文章主要介绍了Powershell SQL SELECT输出到变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在调用查询sql表的函数.我只需要一个细胞的结果.
我无法成功地将单元格数据检索到函数中的变量中.

例如,如果我有一个包含以下内容的表:

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

解决方法

或者,如果您要查找简单的返回值而不是表以便稍后处理,则可以使用以下代码.
[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($1)
    }
    $Connection.Close()
}

猜你在找的MsSQL相关文章