2014-11-05 109 views
1

我需要一種方法,如果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

回答

2

如果發生錯誤,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