4

I have a powershell 2 script that I'm trying to develop. The purpose of this script is to wrap around a batch script and intelligently choose what version of said batch script to run. Somewhere along the lines in my code I have some logic that goes like this:

& $myCommand $args

$myCommand is the fully qualified filename of the batch file I want to run. $args is the args passed into this script. This works except it opens up a command window when running $myCommand. How do I prevent this so that the output is within the same powershell shell?

What's odd is that if I execute the command directly, it shows up the way I want it. So something like:

C:\myCommand.bat $args

Given that I need to choose which command I want to run at runtime, how do I make it so the output is in the same shell when I use the '&' to execute the command in the variable? Thanks!

1 Answer 1

7

Use Start-Process with the -NoNewWindow parameter instead of &:

Start-Process -filepath C:\myCommand.bat -argumentList @("arg1","arg2") -NoNewWindow
Sign up to request clarification or add additional context in comments.

2 Comments

That did the trick. A couple of notes for people who may try this: 1.) The filepath has to include the extension. It is not good enough to have the var set to C:\foo, but it must be set to C:\foo.bat. 2.) This works a lot like adding the & to the end of a BASH command. To have the process called synchronously, you have to supply a -Wait argument. 3.) If you're just wanting to pass the args through, you can put $args instead of @("arg1", "arg2") since $args is a String[].
@JasonThompson everything true, i just specified the array because some people just make $args a string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.