【问题标题】:How to save result from SQL query in Powershell string variable?如何将 SQL 查询的结果保存在 Powershell 字符串变量中?
【发布时间】:2019-07-02 11:11:41
【问题描述】:

我使用invoke-sqlcmd 在MSSMS 上查询数据库。这没问题。 我有一个循环运行查询 X 次,查询返回一个键码,例如。 TGHDWS4.

我需要这个键码作为 powershell 中的字符串。然后我想将字符串添加到数组中。

我唯一尝试过的是使用invoke-sqlcmd。我在网上看到了使用连接创建和连接关闭方法的其他示例,但如果可能的话,我不想这样做。

下面的代码是我所在的位置。如何将键码(从查询返回)作为字符串添加到数组中?

#Enter your confirmation numbers here;
$confArray = @(
'0000000090519838',
'0000000090059392'
)

$resultArray = @()

#Function that runs for each element in the above array
function getKeycode ($confNumber) {


$QueryFmt= "
select distinct top 100       
aa.deliveryKeycode as 'Keycode'
from appointment a with (nolock)
left join appointmentattribute aa with (nolock) on aa.appointmentid = a.appointmentid
where
a.confirmationnumber in (

'"+ $confNumber + "'

)
"

$result = Invoke-Sqlcmd -ServerInstance myserver -Database mydatabase  -Query $QueryFmt

$resultArray.Add($result)

}


#the for loop
foreach($con in $confArray){

getKeycode -confNumber $con
$count ++;

}

【问题讨论】:

    标签: sql powershell invoke-sqlcmd


    【解决方案1】:

    我猜只是从你的函数中返回你的数组:

      # ...
      $result = Invoke-Sqlcmd -ServerInstance myserver -Database mydatabase -Query $QueryFmt 
      $resultArray.Add($result) 
    
      return $resultArray
    }
    

    【讨论】:

    • 我认为因为数组是在函数外部声明的,所以当我在函数内部更改它时,不需要返回它
    【解决方案2】:

    从您的函数写入父范围内的数组有点反模式,我强烈建议不要这样做。

    直接return Invoke-SqlCmd ...

    function Get-Keycode ([int]$confNumber) {
    
      $QueryFmt= "
      select distinct top 100       
      aa.deliveryKeycode as 'Keycode'
      from appointment a with (nolock)
      left join appointmentattribute aa with (nolock) on aa.appointmentid = a.appointmentid
      where
      a.confirmationnumber in (
        '"+ $confNumber + "'
      )"
    
      return Invoke-Sqlcmd -ServerInstance myserver -Database mydatabase  -Query $QueryFmt
    
    }
    
    
    # Assign the output of the foreach loop to `$KeyCodes`
    $KeyCodes = foreach($con in $confArray){
      Get-Keycode -confNumber $con
      $count++
    }
    

    【讨论】:

    • 感谢您的回复 - 我如何绕过获取 System.Data.DataRow 作为响应 - 使用 Write-Host $KeyCodes 时
    • DataRow 的支持属性枚举,所以我会做$KeyCodes.Keycode
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多