如何在从SQL Server 2008 R2作业调用的PowerShell步骤中显示错误?

Syl*_*via 10 sql-server powershell

我一直在网上寻找,但没有找到太多.事实上,大多数信息都出现在stackoverflow上 - 显示通过CMD提示执行Powershell脚本的SQL 2005作业失败,如果PS脚本失败但是SQL Server 2005 失败了,我希望2008年有所改进.

无论如何,如果Powershell脚本失败,我希望能够使SQL Server代理作业失败.在SQL Server中,我使用的是PowerShell步骤,只需:

write-output "this is a test error"
exit -1
Run Code Online (Sandbox Code Playgroud)

我认为这会导致SQL Server作业出错,但它没有发生,它显示成功.是否有必要使用cmdexec步骤,然后shell to powershell,以便能够在它们发生时获得错误?

谢谢,西尔维娅

Gen*_*нин 12

引用Ed Wilson的第10个提示"10.处理SQL Server代理作业中的Windows Powershell错误"来自" SQL Server PowerShell Scripter的10个提示 ":

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'
Run Code Online (Sandbox Code Playgroud)

PS从SqlServerAgent作业返回错误

作业将成功运行,但如果您直接在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'
Run Code Online (Sandbox Code Playgroud)

要将Windows PowerShell错误冒泡到SQL Server代理,您需要执行以下操作之一:

A.设置$ ErrorActionPreference ="停止"

  $erroractionpreference = "Stop"
  get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
Run Code Online (Sandbox Code Playgroud)

B.在cmdlet级别设置ErrorAction(更细粒度)

   get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'  -ErrorAction 'Stop'
Run Code Online (Sandbox Code Playgroud)

C.使用带有ErrorActionPreference或ErrorAction的Try/Catch

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  
}  
Run Code Online (Sandbox Code Playgroud)

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") }
Run Code Online (Sandbox Code Playgroud)


Bru*_*uce 8

如果我希望 Powershell 作业步骤返回错误,我将一行添加到 Write-Error 并将 ErrorAction 设置为停止。这只是一行。

Write-Error "Job Failure" -EA Stop
Run Code Online (Sandbox Code Playgroud)


Bra*_*adC 7

如果您使用“CmdExec”步骤而不是“PowerShell”步骤(由于 PowerShell 版本控制原因,您应该使用“CmdExec”步骤),则以下语法对我有用:

powershell.exe -command "try { & 'D:\BadScript.ps1'} catch { throw $_ }"
Run Code Online (Sandbox Code Playgroud)

(来自乔尔·格雷杰)。