Citando 10 de la punta de Ed Wilson "10. controlar los errores de Windows PowerShell en los trabajos del Agente SQL Server" de "10 Tips for the SQL Server PowerShell Scripter":
10. controlar los errores de Windows PowerShell en los trabajos del Agente SQL Server
Por defecto ErrorActionPreference se establece en Continuar, y esto tiene implicaciones sobre cómo los errores suben al Servidor de tareas de SQL Server. Si ejecuta un comando de Windows PowerShell como trabajo del Agente de SQL Server y todavía no hay errores de sintaxis, el comando produce un error (por ejemplo, intentar obtener información del sistema operativo de un servidor no disponible). El trabajo del Agente SQL Server informará el éxito. Si desea una condición de error para detener la ejecución de un trabajo del Agente SQL Server o para producir un error, deberá agregar algún tipo de manejo de error. Puede configurar un trabajo del Agente SQL Server con Windows PowerShell paso de trabajo de la siguiente manera:
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
se ejecutará el trabajo con éxito, pero si se ejecuta directamente en Windows PowerShell, podrás ver:
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'
burbujear errores de Windows PowerShell para el Agente SQL Server, tendrá que hacer una de las siguientes:
A. Fija tu ErrorActionPreference $ = "Stop"
$erroractionpreference = "Stop"
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
B.Establecer ErrorAction a nivel de cmdlet (más granular)
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
C. Uso try/catch con ErrorActionPreference o ErrorAction
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. continuar, y falle el trabajo del Agente SQL Server
Digamos que tiene una colección de computadoras y desea continuar con el error, pero también quiere dejar el trabajo. En este caso, puede hacer uso de 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") }
Gracias Bruce: ¡esto funcionó! – Sylvia
y cómo verificar el error y devolver el error solo en caso de error? –