Sql server 如何显示从SQL Server 2008 R2作业调用的PowerShell步骤中的错误?
我一直在网上四处寻找,但没有找到太多。事实上,关于stackoverflow的信息最多——但这是SQL Server 2005,我希望2008年的情况有所改善 无论如何,如果Powershell脚本失败,我希望能够使SQL Server代理作业失败。在SQL Server中,我使用的是powershell步骤,其中包括:Sql server 如何显示从SQL Server 2008 R2作业调用的PowerShell步骤中的错误?,sql-server,powershell,Sql Server,Powershell,我一直在网上四处寻找,但没有找到太多。事实上,关于stackoverflow的信息最多——但这是SQL Server 2005,我希望2008年的情况有所改善 无论如何,如果Powershell脚本失败,我希望能够使SQL Server代理作业失败。在SQL Server中,我使用的是powershell步骤,其中包括: write-output "this is a test error" exit -1 我原以为这会导致SQL Server作业出错,但事实并非如此,它显示了成功。是否有必要
write-output "this is a test error"
exit -1
我原以为这会导致SQL Server作业出错,但事实并非如此,它显示了成功。是否有必要使用cmdexec步骤,然后向powershell抛出,以便在错误发生时能够获取错误
谢谢,
Sylvia如果我希望Powershell作业步骤返回错误,我将添加一行以写入错误,并将ErrorAction设置为stop。这只是一条线。
写入错误“作业失败”-EA Stop
我还成功地使用以下代码终止了SQL作业步骤:
if (!$files)
{THROW 'Throw Error: the backup directory was empty!'; "%errorlevel%"}
这用于检查目录($files)中是否有文件,如果为空则抛出错误。它将返回自定义抛出并返回PowerShell退出代码(通过%errorlevel%),导致作业向运行作业并在该步骤结束作业的SQL代理会话返回错误 引用Ed Wilson的第十个技巧“10.处理SQL Server代理作业中的Windows Powershell错误”,来自“”: 10。处理SQL Server代理作业中的Windows Powershell错误 默认情况下,ErrorActionPreference设置为Continue,这对SQL Server作业服务器如何出现错误有影响。如果将Windows PowerShell命令作为SQL Server代理作业运行,并且尚未出现语法错误,则该命令将生成错误(例如,试图从不可用的服务器获取操作系统信息)。SQL Server代理作业将报告成功。如果希望错误条件停止SQL Server代理作业的执行或产生错误,则需要添加一些错误处理。您可以使用Windows PowerShell作业步骤设置SQL Server代理作业,如下所示:
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
作业将成功运行,但如果直接在Windows PowerShell中运行,您将看到:
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
get-wmiobject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
要向SQL Server代理冒泡Windows PowerShell错误,您需要执行以下操作之一:
A.设置$ErrorActionPreference=“Stop”
$erroractionpreference = "Stop"
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
B.在cmdlet级别设置ErrorAction(更细粒度)
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
try
{
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
}
catch
{
throw "Something went wrong"
#or rethrow error
#throw $_
#or throw an error no message
#throw
}
C.将Try/Catch与ErrorActionPreference或ErrorAction一起使用
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
try
{
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
}
catch
{
throw "Something went wrong"
#or rethrow error
#throw $_
#or throw an error no message
#throw
}
D.继续,并使SQL Server代理作业失败
假设您有一组计算机,您希望继续处理错误,但也希望作业失败。在这种情况下,您可以使用ErrorVariable:
#Note the -ErrorVariable parameter takes a variable name without the $ prefix.
get-wmiobject Win32_OperatingSystem -ComputerName 'localhost','nothere','Win7boot' -ErrorVariable myError
if ($myError)
{ throw ("$myError") }
如果您使用的是“CmdExec”步骤而不是“PowerShell”步骤(您应该这样做),则以下语法适用于我:
powershell.exe -command "try { & 'D:\BadScript.ps1'} catch { throw $_ }"
(from)。以及如何检查错误并仅在出现错误时返回错误?在我看来,这是正确的方法。