Comet
Comet

Reputation: 288

How to read PowerShell StdOut

I have code to invoke CreateProcess() and get the handles for StdIn & StdOut. I have used it with CMD and it works fine. However, I started PowerShell with it and PowerShell did not play nice. It basically exploited my program and took over the thread.

This led me to debug of course and I found that as soon as the ReadFile() function reads PowerShells output, it's all over. Interesting.

So my question is: In what format does PowerShell send output to StdOut?

I heard it talks in "Objects", but it seems to output raw machine code.

DWORD WINAPI threadRead(HANDLE *cmdStd_OUT_RD) {
    char *chBuff = malloc(READ_BUFFER_SM);
    int check = 0;
    for (;;) {
        dwRead = 0;  //Global Variable
        check = 0;
        memset(chBuff, 0, READ_BUFFER_SM);
        puts("Reading..\n");
        check = ReadFile(*cmdStd_OUT_RD, chBuff, READ_BUFFER_SM, &dwRead, NULL);
        if (check || dwRead > 0) {
            printf("Display: %s\n", chBuff);
        }
    }
    return 0;
}

Also, Is there another Read function that is safe for PowerShell?

Edit: I feel like it is sending bytes so might try using a void. Will update after.

Edit: No, it still takes over. Guess ReadFile() cannot read its StdOut.

Upvotes: 0

Views: 1870

Answers (1)

Gonçalo Garrido
Gonçalo Garrido

Reputation: 118

Try reading this : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6?

And try this:

$OutputVariable = (Shell command) | Out-String

or

"$params = "/verify $pc /domain:hosp.uhhg.org"
start-process "netdom.exe" $params -WindowStyle Hidden -Wait"

Upvotes: 1

Related Questions