PowerShell keep printing 1 before expected output

I had written a script to parse the contents of a URL and store the contents in a SQL Server table. The script has a couple of write-host commandlets to track the progress of the script. Here is a snippet of the script.

However on executing the script, before the write-host commandlet a couple of “1” would be written in the console. I had nowhere written in the script to write “1” to the console!

On having a closer look, I realized that the SqlCommand.ExecuteNonQuery method was the culprit. Here is why. As per the documentation, the return value of SqlCommand.ExecuteNonQuery method will always be the number of rows affected. Hence whenever I had executed ExecuteNonQuery, the number of rows affected (in my case 1) would be returned. Now that I have nailed down the ghost 1 output, the resolution was simple.

Just pipe the SqlCommand.ExecuteNonQuery with Out-Null cmdlet which hides the output instead of sending to the pipeline or displaying it. Following is the modified version of the script.

Now the script just prints what I had expected it to.

By | 2017-05-15T10:26:40+00:00 May 15th, 2017|languages, Scripts|1 Comment

One Comment

  1. reko91 March 12, 2018 at 8:10 pm - Reply

    helped me out, thank you

Leave A Comment