从批处理脚本调用PowerShell脚本

问题描述:

我需要一种方法,如果PowerShell脚本因任何原因失败,就能够批处理脚本退出并写入日志文件。从批处理脚本调用PowerShell脚本

现在我有一些与此类似:

SET DBSCRIPT=C:\Scripts\UpdateAppDB.ps1 
IF EXISTS %DBSCRIPT% (
    POWERSHELL -Command %DBSCRIPT% 
) ELSE (
    ECHO "Script not found." >> C:\TestResults\TestLog.txt` 
    EXIT 
) 

有什么办法来处理PowerShell的运行过程中可能出现的错误?

+0

不POWERSHELL设置* errorlevel *,你可以测试吗? '如果错误级别1变坏了'。如果没有其他回报,可能需要您“致电”POWERSHELL。 – 2014-11-05 18:17:14

+0

它没有,但如果不可能像批处理try> catch那样做,我可以修改powershell来抛出退出代码或其他东西。 – 2014-11-05 18:21:02

+0

@SeanLong是的,你的脚本应该以适当的状态码退出。批处理没有异常处理。它只能对外部命令返回的内容作出反应。 – 2014-11-05 18:23:34

如果发生错误,PowerShell命令应返回退出代码> 0。您可以处理,像这样:

set "DBSCRIPT=C:\Scripts\UpdateAppDB.ps1" 
if exists %DBSCRIPT% (
    powershell -Command %DBSCRIPT% || ( rem Error handling routines here ) 
) else (
    echo "Script not found." >> C:\TestResults\TestLog.txt 
    exit 
)

或像这样(需要延迟启用扩展):

setlocal EnableDelayedExpansion 

set "DBSCRIPT=C:\Scripts\UpdateAppDB.ps1" 
if exists %DBSCRIPT% (
    powershell -Command %DBSCRIPT% 
    if !errorlevel! neq 0 ( rem Error handling routines here ) 
) else (
    echo "Script not found." >> C:\TestResults\TestLog.txt 
    exit 
)

作为一个侧面说明:因为你想运行PowerShell脚本我会使用powershell -File "%DBSCRIPT%"代替powershell -Command "%DBSCRIPT%"。变量周围的双引号关心路径中的潜在空间。

编辑:要清楚,上面的代码只处理来自PowerShell可执行文件或PowerShell脚本的非零返回代码。它不会(也不能)替换PowerShell脚本中的错误处理。如果你想PowerShell脚本终止所有的错误(和指示与非零退出代码的错误状态),你至少需要像这样的PowerShell脚本:

$ErrorActionPreference = "Stop" 
try { 
    # ... 
    # rest of your code here 
    # ... 
} catch { 
    Write-Error $_ 
    exit 1 
} 
+0

我想'ERRORLEVEL'在这里代表PowerShell本身返回的内容,而不是PowerShell脚本所做的。只要PowerShell启动并尝试运行脚本文件,无论脚本中出现任何错误,“ERRORLEVEL”都将变为“0”。 – aphoria 2014-11-05 19:05:50

+0

正确。批处理无法替换PowerShell脚本中的错误处理。它只能对脚本返回的内容做出反应。 – 2014-11-05 22:29:42