Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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=''
share|improve this question
1  
If you build the string outside the loop then $item is null – EBGreen Aug 16 '13 at 18:17

2 Answers 2

up vote 1 down vote accepted

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
share|improve this answer
    
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. – Colin Aug 16 '13 at 17:53
    
You built the string outside of the loop. – EBGreen Aug 16 '13 at 18:16
    
You got it! ...I feel stupid. – Colin Aug 16 '13 at 18:18
    
@ColinA.White Don't, because you're not. We've all facepalmed – Colyn1337 Aug 16 '13 at 18:57
    
not me. I usually need the whole fist not just the palm – EBGreen Aug 16 '13 at 19:15

$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

}
share|improve this answer
    
Just seen that @EBGreen answered as I typing. – RobertKenny Aug 16 '13 at 18:24
    
Nothing wrong with having multiple answers! – Hyper Anthony Aug 16 '13 at 18:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.