[英]How capture errorlevel of powershell script in a batch file when execute as 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
我不要 你能幫我嗎?
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
==>
說明
在PowerShell
$?
如果上一次操作成功,則包含True
,否則包含False
。最后一個Win32可執行文件執行的退出代碼存儲在自動變量
$LASTEXITCODE
要讀取退出代碼(非
0
或1
),請啟動PowerShell腳本,並在$LASTEXITCODE
中返回$LASTEXITCODE
,如下所示:powershell.exe -noprofile C:\\scripts\\script.ps1; exit $LASTEXITCODE
-PassThru
為該cmdlet啟動的每個進程返回一個
System.Diagnostics.Process
進程對象。 默認情況下,此cmdlet不會生成任何輸出。
-Wait
指示此cmdlet在接受更多輸入之前等待指定的過程完成。 此參數禁止顯示命令提示符或保留窗口,直到過程完成。
(call )
:Dave Benham答復了將ERRORLEVEL設置為0的問題:
如果要將錯誤
errorlevel
強制設置為0
,則可以使用以下完全不直觀但非常有效的語法:(call )
。 通話后的空間至關重要。 如果要將錯誤errorlevel
設置為1
,則可以使用(call)
。 呼叫后必須沒有空格是至關重要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.