2

This is my code:

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\

When executed in powershell, the system opens a Command prompt window and executes the bat file without issue. The problem is that the window closes and I cannot see if there was an error if it succeeds.

I want to keep the CMD window open.

I also tried at the end of the bat file:

:END
cmd /k

but no luck.

1
  • Pause will do the trick. Most commands of cmd are also supported on powershell. So u dont need to invoke a cmd from powershell. You can directly run on powershell or even translate it to powershell. That way, you can perform error handling and such Commented May 29, 2020 at 20:09

2 Answers 2

3

First, unless you specifically need to run the batch file in a new window, do not use Start-Process - use direct invocation instead, which is implicitly synchronous and allows you to capture or redirect output:

# Invoke the batch file synchronously (wait for it to exit)
# and capture its (standard) output in variable $A
# To print the batch file's output to the console instead, just use:
#    .\refresh.bat
$A = .\refresh.bat

See this answer for more information.

Also note Start-Process never allows you to capture the invoked program's output directly (you can only redirect it to files with -RedirectStandardOutput and -RedirectStandardOutput); your specific command captures nothing[1] in $A; adding -PassThru does return something, but not the program's output, but a process-information object (System.Diagnostics.Process).

If you do need to run the batch file in a new window and want to keep that window open:

Start-Process -Wait -FilePath cmd -ArgumentList '/k .\refresh.bat'

Relying on positional parameter binding, the above can be simplified to:
Start-Process -Wait cmd '/k .\refresh.bat'


[1] Strictly speaking, $A is assigned the [System.Management.Automation.Internal.AutomationNull]::Value singleton, which in most contexts behaves like $null.

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you mklement0 with your post gave me the solution I wanted. This is how I solved it.

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait -NoNewWindow
set-location C:\

-NoNewWindow allowed me to run my batch in the same powershell window getting the feedback of the bat file. That way I have errors if any and success status if no errors.

Thanks!

1 Comment

Glad to hear my answer was helpful - note that a simpler alternative is to use direct invocation without capturing the output: .\refresh.bat by itself is enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.