Redirect Input and Output of Powershell.exe to Pipes in C++

Question:

I am trying to execute powershell commands in C++ and get its output through pipes.

My program works perfectly for cmd.exe. However, when I try to do the same thing with powershell.exe, I only get “W” as an output.

I have commented the line in the code below that needs to be modified to execute powershell.exe
Below is my code that works for cmd.exe:

If the CreateProcess() is used for powershell, it does not work the same way, but I get only W as output.

What is the reason for this?
And
How to get over this problem?

EDIT 1 : If I display the output_cmd in a loop character by character as output_cmd[i] where i = 0 to strlen(output_cmd), I get an output as given below:

i n d o w s P o w e r S h e l l
C o p y r i g h t ( C ) 2 0 1 4 M i c r o s o f t C o r p o r a t i o n . A l l r i g h t s r e s e r v e d .

P S C : \ W i n d o w s >

and the application hangs after that! It doesn’t take in any input, or give any output after that!

Answer:

You passed string to wrong place:

CreateProcess(TEXT("C:\\Windows\\System32\\cmd.exe")

actually the first parameter should be NULL:
CreateProcess(NULL, TEXT("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe")

Source:

Redirect Input and Output of Powershell.exe to Pipes in C++ by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply