0

I using invoke-sqlcmd to query a database on MSSMS. This works no problem. I have a loop that runs the query X amount of times and the query returns a keycode eg. TGHDWS4.

I need this keycode as a string in powershell. I then want to add the string to an array.

The only thing i've tried is using invoke-sqlcmd. I have seen other examples on the net that use connection creation and connection close methods but i dont want to have to do that if possible.

The below code is where i'm at. How do I add the keycode (returned from the query) to an array as a string?

#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 ++;

}
Cormac
  • 25
  • 8

2 Answers2

1

I guess by just returning your array from within your function:

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

  return $resultArray
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
JKoopman
  • 36
  • 2
  • I thought because the array is declared outside the function that when i change it inside the function there is no need to return it – Cormac Jul 02 '19 at 11:27
0

Writing to an array in the parent scope from your function is a bit of an anti-pattern, I'd strongly advise against it.

Just return Invoke-SqlCmd ... directly:

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++
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206