2

I'm trying to launch a batch file (with administrative mode) in Powershell. I need the output of the batch file to be within the Powershell console.

I'm able to launch the batch file as administrator using

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

However the output is not in Powershell but command prompt itself.

I've tried the following command to launch the command prompt directly. The result is the same.

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

If I try the following command: PS> &C:\Scripts\test.bat

I will be able to run the batch file with the console output but I will not be able to launch it properly because I need the administrative rights.

Is there a way to launch the batch file with administrative rights and see the output in Powershell console as well?

2 Answers 2

1

You could redirect batch-file output to a file and then show it in Powershell.

powerShell -Command "&{Start-Process 'cmd.exe' /c C:\Scripts\test.bat >outputfile' -Verb runas -Wait}"
get-content outputfile
Sign up to request clarification or add additional context in comments.

Comments

1

Another alternative is that you can write a powershell script that runs cmd with your bat script as argument :

$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

1 Comment

I've tried your method. I'm unable to launch my application which is in the batch file from powershell. But I will be keen to try out :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.