[英]SQL Server backup using powershell in Task scheduler
I am using PowerShell to backup a SQL Server database and use Windows task scheduler to schedule the script我正在使用 PowerShell 备份 SQL 服务器数据库并使用 Windows 任务计划程序来安排脚本
Test测试
Run the script manually, it works.手动运行脚本,它有效。
Both SQL Server backup file ( test.bak
) and test file ( HelloWorld.txt
) were created. SQL 服务器备份文件 ( test.bak
) 和测试文件 ( HelloWorld.txt
) 均已创建。
Run via Windows task scheduler, only HelloWorld.txt
was created, the SQL Server backup file was not created.通过 Windows 任务调度程序运行,只创建了HelloWorld.txt
,没有创建 SQL 服务器备份文件。
So at least;至少如此;
Problem问题
Why is the SQL SErver backup file not created when run from Windows task scheduler?为什么从 Windows 任务计划程序运行时没有创建 SQL SErver 备份文件?
Here is my SQLbackup.ps1
file:这是我的SQLbackup.ps1
文件:
$credential = import-clixml -path c:\pp\test\sqlcred.xml
Backup-SqlDatabase -ServerInstance Server264\SUPPORT2K19 -Database PPTest -BackupAction Database -BackupFile "C:\PP\Test\Test.bak" -Credential $credential
Set-Content -Path "C:\PP\Test\HelloWorld.txt" -Value "Hello World"
Task scheduler settings are:任务计划程序设置为:
In action tab:在操作选项卡中:
-executionpolicy bypass -file C:\PP\Test\sqlbackup.ps1
添加arguments: -executionpolicy bypass -file C:\PP\Test\sqlbackup.ps1
Any suggestion why the SQL Server backup file was not created?为什么没有创建 SQL 服务器备份文件的任何建议?
I think the cmdlet Backup-SqlDatabase
produce an error, and you do not have a mechanism to capture that.我认为 cmdlet Backup-SqlDatabase
会产生错误,而您没有捕获该错误的机制。
Try implementing try/catch
to capture the error and then you can do what you want with that information, for example:尝试实现try/catch
来捕获错误,然后您可以使用该信息执行您想要的操作,例如:
$credential = import-clixml -path c:\pp\test\sqlcred.xml
try {
Backup-SqlDatabase -ServerInstance Server264\SUPPORT2K19 -Database PPTest -BackupAction Database -BackupFile "C:\PP\Test\Test.bak" -Credential $credential -ErrorAction Stop
}
catch {
Set-Content -Path "C:\PP\Test\Error.txt" -Value "$_"
}
Set-Content -Path "C:\PP\Test\HelloWorld.txt" -Value "Hello World"
This would capture the potential error
and write it in a Error.txt
file, same way as the HelloWorld.txt
.这将捕获潜在的error
并将其写入Error.txt
文件,与HelloWorld.txt
相同。
Important part is that Try/Catch
capture only terminating errors, so we add the -ErrorAction Stop
at the end of the cmdlet to make any error terminating so we can execute the script in the catch
script block.重要的部分是Try/Catch
仅捕获终止错误,因此我们在 cmdlet 的末尾添加-ErrorAction Stop
以使任何错误终止,以便我们可以在catch
脚本块中执行脚本。
You can read more about it in the Microsoft docs: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.2您可以在 Microsoft 文档中阅读更多相关信息: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.2
PS The documentation is for Powershell 7.2 PS 该文档适用于 Powershell 7.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.