1

I created array $SQL_output. If I do a foreach loop, it displays the contents

foreach ($j in $SQL_output){
    write-host $j
}

Output

118543
44021
84992
46888

When I add it to SQL statement

$SQL_UPDATE = "BEGIN
                  IF NOT EXISTS (SELECT 1
                                 FROM dbo.Stats
                                 WHERE Date_of_Download = CAST(GETDATE() AS DATE))
                  BEGIN
                      INSERT INTO dbo.Stats (Date_of_Download, Windows_SEP_11, Mac_SEP_11, Windows_SEP_12, Mac_SEP_12)
                      VALUES (CAST(GETDATE() AS DATE), $SQL_output[0],$SQL_output[1],$SQL_output[2],$SQL_output[3])
                  END
              END
"

The string expands to

BEGIN
                  IF NOT EXISTS (SELECT 1
                                 FROM dbo.Stats
                                 WHERE Date_of_Download = CAST(GETDATE() AS DATE))
                  BEGIN
                      INSERT INTO dbo.Stats (Date_of_Download, Windows_SEP_11, Mac_SEP_11, Windows_SEP_12, Mac_SEP_12)
                      VALUES (CAST(GETDATE() AS DATE), 118543 44021 84992 46888[0],118543 44021 84992 46888[1],118543 44021 84992 46888[2],118543 44021 84992 46888[3])
                  END
              END

How to fix?

6
  • 2
    Use $($SQL_output[0]). Or use -f to format the string and use the expansions as arguments. Commented May 19, 2015 at 17:28
  • 2
    possible duplicate of Referencing Powershell array index produces unexpected results when referenced with string Commented May 19, 2015 at 17:29
  • @EtanReisner This works, can you explain why. First time I am seeing this notation. Commented May 19, 2015 at 17:29
  • 1
    See the linked issue. You need to show powershell how to parse the variable (it stops early by default). Commented May 19, 2015 at 17:31
  • 1
    Another useful link: stackoverflow.com/questions/1145704/… Commented May 19, 2015 at 17:58

1 Answer 1

1

Replace $SQL_output[x] with $(SQL_output[x])

$SQL_UPDATE = "BEGIN
              IF NOT EXISTS (SELECT 1
                             FROM dbo.Stats
                             WHERE Date_of_Download = CAST(GETDATE() AS DATE))
              BEGIN
                  INSERT INTO dbo.Stats (Date_of_Download, Windows_SEP_11, Mac_SEP_11, Windows_SEP_12, Mac_SEP_12)
                  VALUES (CAST(GETDATE() AS DATE), $($SQL_output[0]),$($SQL_output[1]),$($SQL_output[2]),$($SQL_output[3]))
              END
          END
"
Sign up to request clarification or add additional context in comments.

Comments

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.