Powershell Sql query Timing out

Code below work fine. But there arew times it falls into issues. The issues is with the timeout value. Is there a way have it not time out. There are times the query can take 2 or 3 minutes and theirs no issue.Sometimes query can take 3 to 6 hours and it works its just that theres a lot of records to process in SQL Studio the query works fine no timeout. When it starts to take that long when executed from Powershell it timesout.

My question is how to I code this so it does not time out. I put in a parameter but it a time value for time out can I have it where it wont time out and let the query run its course.

add-pssnapin sqlserverprovidersnapin100 -ErrorAction SilentlyContinue
add-pssnapin sqlservercmdletsnapin100 -ErrorAction SilentlyContinue

$Servers = Get-Content "C:\NOCScripts\SQL\AuditPending\AuditPendingLog.txt"

Foreach($server in $Servers){

invoke-sqlcmd -inputfile "C:\NOCScripts\SQL\AuditPending\AuditRecords.sql" -serverinstance $server -database "master" -QueryTimeout 20000 


Open in new window

Leo TorresSQL DeveloperAsked:
Who is Participating?
Bob LearnedCommented:
I believe that before SQL Server 2012, the minimum timeout value was 0, so you would have to set the timeout very high.  The max value appears to be 65534.
Bob LearnedCommented:
What version of SQL Server are you using?

According to this Connect article, you should be able to use query timeout of 0 in SQL Server 2012 and higher.

invoke-sqlcmd -querytimeout 0 still times out
Leo TorresSQL DeveloperAuthor Commented:
using 2008 mostly few 2005.
Have not tried -querytimeout 0 option will to that today. and keep you posted.

Leo TorresSQL DeveloperAuthor Commented:
OK great I will go with that for now. I Have not been able to test.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.