Mau*_*rdo 2 windows powershell cmd batch-file
当以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%
输出量
Write-Host "executed: $($MyInvocation.Line)"
# pause
Exit 123+[int]([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::
    GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")
说明
在PowerShell中
$?包含True上一次操作是否成功,False否则。最后一个Win32可执行程序执行的退出代码存储在自动变量中
$LASTEXITCODE要读取退出代码(不是
0或1),请启动PowerShell脚本,并$LASTEXITCODE在单行中返回,如下所示:Run Code Online (Sandbox Code Playgroud)powershell.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE
-PassThru
System.Diagnostics.Process为cmdlet启动的每个进程返回一个进程对象。默认情况下,此cmdlet不会生成任何输出。
-Wait指示此cmdlet在接受更多输入之前等待指定的过程完成。此参数禁止显示命令提示符或保留窗口,直到过程完成。
(call ):Dave Benham答复将ERRORLEVEL设置为0问题:
如果要强制使用
errorlevelto0,则可以使用以下完全不直观但非常有效的语法:(call )。通话后的空间至关重要。如果要设置errorlevel为1,可以使用(call)。呼叫后必须没有空格是至关重要的 。
| 归档时间: | 
 | 
| 查看次数: | 2258 次 | 
| 最近记录: |