2017-06-17 35 views
1

我需要在以admin身份執行時捕獲批處理文件中powershell腳本的輸出。當以admin身份執行時,如何捕獲批處理文件中powershell腳本的錯誤級別

例子:

PS1文件:

Write-Host "PS1 executed" 
exit 1 

如果我執行PowerShell腳本沒有管理員權限

NotAdminFile.bat:

@ECHO OFF 
setlocal enableextensions 
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'" 
echo %ERRORLEVEL% 
endlocal 

然後,輸出是

PS1 executed 
1 

這沒關係。 但是,當我執行PowerShell腳本擁有管理員權限的

AdminFile.bat:

@ECHO OFF 
setlocal enableextensions 
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "%~dpn0.ps1" ' -Verb RunAs}" 
echo %ERRORLEVEL% 
endlocal 

然後,輸出是:

0 

,我不希望出現這種情況。你能幫我嗎?

+0

IMO它**是** OK,因爲批錯誤級別反映PowerShell運行啓動過程沒有錯誤。 – LotPings

回答

3

exit_1_only.ps1

Write-Host "executed: $($MyInvocation.Line)" 
# pause 
Exit 123+[int]([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]:: 
    GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator") 

q44600354.bat

@ECHO OFF 
SETLOCAL EnableExtensions DisableDelayedExpansion 

(call) 
echo errorlevel clear=%errorlevel% 

PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command^
    "& 'D:\PShell\tests\exit_1_only.ps1'; exit $LASTEXITCODE" 
echo errorlevel non-admin=%errorlevel% 

echo(
(call) 
echo errorlevel clear=%errorlevel% 

PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command^
    "& {exit (Start-Process -Wait -PassThru -FilePath PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -Command ""D:\PShell\tests\exit_1_only.ps1; exit $LASTEXITCODE"" ' -Verb RunAs).ExitCode}" 
echo errorlevel admin=%errorlevel% 

輸出

==> D:\bat\SO\q44600354.bat 
errorlevel clear=0 
executed: & 'D:\PShell\tests\exit_1_only.ps1'; exit $LASTEXITCODE 
errorlevel non-admin=123 

errorlevel clear=0 
errorlevel admin=124 

==> 

說明

Exit Codes

在PowerShell中$?包含True如果上一操作成功和 False否則。

最後Win32可執行程序執行的退出代碼被存儲在 自動可變$LASTEXITCODE

要閱讀的退出代碼(除01其他)啓動的PowerShell 腳本和在像單個線返回$LASTEXITCODE這樣的:

powershell.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE 

Start-Process

-PassThru

返回System.Diagnostics.Process進程對象爲每個進程 的cmdlet的開始。默認情況下,此cmdlet不會生成任何 輸出。

-Wait

表示此cmdlet等待指定的過程接受更多輸入之前完成 。該參數禁止命令 提示或保留該窗口,直到過程完成。

(call):戴夫·貝納姆在回答設置ERRORLEVEL爲0問題:

如果要強制errorlevel0,那麼你可以使用這個 完全非直觀的,但很有效的語法:(call)之後的空間 致電至關重要。如果要將errorlevel設置爲1, ,則可以使用(call)請致電之後沒有空間是非常重要的。

+0

完美!謝謝您的幫助。 –

+0

男人,我會upvote這個答案10倍,如果我可以...我已經失去了將近_a day_追逐'RunAs'的PowerShell退出代碼...謝謝! –

相關問題