Powershell SqlCmd - Using result values without defining variables

KickinMhl picture KickinMhl · Jun 12, 2013 · Viewed 16.5k times · Source

I am wondering if there is any way to use values for a dataset in a subsequent query.
Here is an example:

Works:

$Result = Invoke-Sqlcmd -query "SELECT Id, FirstName, LastName FROM Person" 
foreach($item in $Result){
  $ID= $item.Id 
  $SaleResults = Invoke-Sqlcmd -query "SELECT * FROM Sales WHERE Salesperson = $ID"
}

Does NOT Work:

foreach($item in $Result){
  $SaleResults = Invoke-Sqlcmd -query "SELECT * FROM Sales WHERE Salesperson=$Item.Id"
}

The second example fails because it is using $Item.Id as a string rather that uniqueidentifier, hence the error: "Conversion failed when converting from a character string to uniqueidentifier."

Any idea how to use these values with their correct type, without creating a separate variable?

Answer

Mike Shepard picture Mike Shepard · Jun 12, 2013

You need to use $($Item.ID) in your double-quoted string, and it will work.