15

I am trying to execute an external command using powershell, without having the second program to popup, I need to execute this program within the same PowerShell window and output both the log and the errors. I started with this:

$outcome = Start-Process -Wait -FilePath "cmd.exe" -ArgumentList "dir" -NoNewWindow 2>&1
$outcome

But it doesn't work as expected. I still see the new window popping up with DOS and no redirect at all about the output, the errors and so on. Am I doing something wrong?

3
  • 1
    Could you use Invoke-Expression instead? Commented Feb 10, 2014 at 12:56
  • Yes I can but all the examples I found are Start-Process related ... Commented Feb 10, 2014 at 15:32
  • Invoke-Expression "$PWD\.venv\Scripts\Activate.ps1" worked for me in my use case. Commented Jan 4 at 7:51

3 Answers 3

18

Does this work for you?

$outcome = Invoke-Expression "cmd.exe /c dir"
$outcome
Sign up to request clarification or add additional context in comments.

Comments

2

My suggestion is to use the call operator

& cmd.exe /c dir

Comments

-2

You can just run it. You're missing "/c". Otherwise, it just runs "cmd".

$outcome = cmd /c dir

With the added complication of start-process, you'd have to save the output to a file.

Start-Process -Wait -FilePath "cmd.exe" -ArgumentList "/c","dir" -NoNewWindow -RedirectStandardOutput cmd.log -RedirectStandardError err.txt

or

Start-Process -Wait -FilePath cmd.exe -Args "/c dir >cmd.log 2>&1" -NoNewWindow

Comments

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.