Cormac
Cormac

Reputation: 25

How to save result from SQL query in Powershell string variable?

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

}

Upvotes: 0

Views: 2532

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

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++
}

Upvotes: 0

JKoopman
JKoopman

Reputation: 36

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
}

Upvotes: 1

Related Questions