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
Question
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=''
La solution
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
Autres conseils
$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
}