如何在管理模式下在Powershell中输出批处理文件的控制台?

时间:2019-04-11 08:27:58

标签: powershell batch-file

我正在尝试在Powershell中启动批处理文件(具有管理模式)。我需要批处理文件的输出在Powershell控制台中。

我可以使用

以管理员身份启动批处理文件

PS> Start-Process "C:\Scripts\Test.bat" -Verb runas

但是输出不是在Powershell中,而是命令提示符本身。

我尝试了以下命令来直接启动命令提示符。结果是一样的。

PS> powerShell -Command "&{Start-Process 'cmd.exe' /c C:\Scripts\test.bat' -Verb runas}"

如果我尝试以下命令: PS> &C:\Scripts\test.bat

我将能够通过控制台输出运行批处理文件,但由于需要管理权限,因此我将无法正确启动它。

是否可以使用管理权限启动批处理文件并在Powershell控制台中查看输出?

2 个答案:

答案 0 :(得分:1)

您可以将批处理文件输出重定向到文件,然后在Powershell中显示。

powerShell -Command "&{Start-Process 'cmd.exe' /c C:\Scripts\test.bat >outputfile' -Verb runas -Wait}"
get-content outputfile

答案 1 :(得分:1)

另一种替代方法是,您可以编写一个cmd脚本作为参数运行bat的powershell脚本:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "cmd.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/c C:\Scripts\test.bat"
$pinfo.Verb = "runas" # for elevation 
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode