1

I'm not getting any output from this script. Not even an error msg... I think my problem is the use of a variable in the WHERE clause. I've tried escaping this $(item) with backtics but making no progress. Can anyone help me understand what I'm doing wrong?

$dbserver   = "AHDC389"
$dbase  = "FOO"
$table  = "$($dbase).dbo.BAR"

Import-Module “sqlps” -DisableNameChecking

$myArray    = @(Invoke-Sqlcmd "Select myColumn From adifferentserver.dbo.[mylookuptable]") | select-object -expand myColumn

ForEach ($item in $myyArray) {

    Invoke-Sqlcmd "Select * FROM $table Where FacilityID='$(item)' "

}

UPDATE:

So when I modify the script like below, is seems the variable for the Where= is not expanding out.

$dbserver   = "AHDC389"
$dbase  = "FOO"
$table  = "$($dbase).dbo.BAR"

Import-Module “sqlps” -DisableNameChecking

$myArray    = @(Invoke-Sqlcmd "Select myColumn From adifferentserver.dbo.[mylookuptable]") | select-object -expand myColumn

$myQuery    = "Select * FROM {0} Where FacilityID='{1}'" -f $table, $item

ForEach ($item in $mArray) {

    Write-Host $myQuery
    #Invoke-Sqlcmd $myQuery

}

The value of $myQuery is returned to the console indicating the $item is not being expanded:

Select * FROM  FOO.dbo.BAR Where Facility=''
1
  • 1
    If you build the string outside the loop then $item is null Commented Aug 16, 2013 at 18:17

2 Answers 2

1

It is simply personal preference, but I build the string using the -format operator:

$cmdStr = 'Select * FROM {0} WHERE FacilityID={1}' -f $table, $item
Write-Host 'Executing: ' + $cmdStr
Invoke-Sqlcmd $cmdStr
Sign up to request clarification or add additional context in comments.

3 Comments

I still get no output to the console when I do this. I suspect he problem is the need for TSQL to use the ' in the WHERE='foo' clause.
You built the string outside of the loop.
@ColinA.White Don't, because you're not. We've all facepalmed
0

$item is not defined until the ForEach loop so it cannot be used in the assignment prior to that. Move the declaration into the loop.

ForEach ($item in $mArray) {
$myQuery    = "Select * FROM {0} Where FacilityID='{1}'" -f $table, $item

Write-Host $myQuery
#Invoke-Sqlcmd $myQuery

}

1 Comment

Just seen that @EBGreen answered as I typing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.