通过“调用-Sqlcmd”运行“ SQL Server备份”,使“执行超时到期”

时间:2018-09-27 20:56:47

标签: sql-server powershell

免责声明:我是Powershell的新手。

我正在尝试使用从Powershell运行的SQL脚本为两个SQL Server Express数据库的备份编写脚本。当我从SSMS运行SQL时,它运行良好且没有超时。当我从Powershell脚本运行SQL时,小型数据库备份成功,但是较大的数据库备份失败,并出现以下错误:

Invoke-Sqlcmd : Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
At C:\Program Files\DBBackups\dbfull_backup.ps1:5 char:1
+ Invoke-Sqlcmd -ServerInstance "$serverInstance" -InputFile "C:\Program Files\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

这是.ps1脚本的第5行,该脚本具有Invoke-SqlCmd:

Invoke-Sqlcmd -ServerInstance "$serverInstance" -InputFile "C:\Program Files\DBBackups\dbfull_backups.sql" -Variable $sqlVariable -Verbose *> $outputFile

这是来自SQL的BACKUP命令:

BACKUP DATABASE FrameStore TO DISK = @framestore_backup_file;

通过Powershell / Invoke-Sqlcmd运行时的超时与从SSMS运行时的超时不同吗?在SSMS中运行时,备份需要不到3分钟的时间,因此与我在docs.microsoft文档中看到的10分钟的数字不太接近。这是在SSMS中运行时的备份输出:

BACKUP DATABASE successfully processed 467003 pages in 176.917 seconds (20.622 MB/sec).

版本信息:
作业系统:Windows Server 2012 R2
MS SQL Server Express 2017
PSVersion 4.0

(我很抱歉,如果已经在另一个SO页面中解决了这个问题。尽管看起来很基本,我找不到这个特定问题。)

编辑:
我继续尝试将-QueryTimeout参数设置为3600秒。这样可以成功备份而不会出现错误。那么,默认值是什么?

根据Microsoft Docs page for Invoke-Sqlcmd -QueryTimeout parameter

  

指定查询超时之前的秒数。如果未指定超时值,则查询不会超时。

那么...如果这是真的,而我没有指定超时,为什么会超时呢?从PS版本4更改为记录的版本吗?在备份上设置超时似乎是不好的做法?我对此有意见。它现在可以使用,但是我对我的解决方案仍然没有信心(解决方法?)。

2 个答案:

答案 0 :(得分:5)

因此您已经达到了著名的SMO对象30秒超时。

格兰特·弗里奇(Grant Fritchey)早在2010年就写过这本书。请在此处阅读:https://www.scarydba.com/2010/04/16/powershell-smo-problem/

如果将其设置为0-您将要求它无限运行。

有关此内容的最新博客文章:https://fbrazeal.wordpress.com/2015/06/29/sqlps-tips/

已编辑:

根据所运行的版本,还应该阅读以下内容:https://blogs.technet.microsoft.com/heyscriptingguy/2013/05/06/10-tips-for-the-sql-server-powershell-scripter/

答案 1 :(得分:1)

长问题简短回答 您需要使用参数-Querytimeout X,其中X是以秒为单位的时间

有问题的查询将像这样工作,其中0使无限超时,我们可以使用1到65535之间的整数值。

Invoke-Sqlcmd -ServerInstance "$serverInstance" -Querytimeout 0 -InputFile "C:\Program Files\DBBackups\dbfull_backups.sql" -Variable $sqlVariable -Verbose *> $outputFile