0

我使用 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 ++;

}
4

2 回答 2

1

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

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

  return $resultArray
}
于 2019-07-02T11:20:48.867 回答
0

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

直接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++
}
于 2019-07-02T11:34:35.353 回答