powershell.exe command fails when there is a pipe in the command using system for execution

SilverChips 71 Reputation points
2021-02-07T07:46:27.883+00:00

I am trying to run a powershell command like this

std::string str = "powershell.exe -executionPolicy bypass Select-String -Path C:\\myfile.txt -Pattern \"output:\" | Select -ExpandProperty  > c:\\result.txt";

system(str.c_str());

This command fails and the reason it fails is because there is a pipe so result.txt is always empty.
Any idea why this happens and how I can fix this ?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-02-07T08:52:16.9+00:00

    Try using “^|” instead of “|” and show the results.

    1 person found this answer helpful.

  2. Anonymous
    2021-02-08T03:53:44.817+00:00

    Hi,

    Please check if this works

    powershell.exe -executionPolicy bypass -command "& {Select-String -Path C:\\myfile.txt -Pattern \"output:\" | Select -ExpandProperty Line  > c:\\result.txt}"  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.