1

I need to make PowerShell on Windows Server 2019 to read from a (not named) pipe and launch the commands it reads, so I'll be able to launch multiple commands on the same shell, even without knowing them ahead.
Normal pipe makes it exit (probably on EOF, didn't see an error), I tried a way I thought would work, but it takes 100% CPU which is way too much:

-command 'while ($true) {$command = read-host; 
if ($command) {invoke-expression -Command $command}}'

How could I do this? is this even possible?

Rohit Gupta
  • 134
  • 1
  • 2
  • 12
Didi Kohen
  • 121
  • 6

1 Answers1

0

You could put the logic into a function rather than a while loop. This way you could call the function as-needed to type in the command. You could even put the function into a script, dot source it, and then call the function when you are ready to type in the previously unknown command.

PowerShell

Function Command () {
    $command = read-host;
    invoke-expression -Command "$command";
    };

Command;

If you put this into C:\Scripts\command.ps1

Function Command () {
    $command = read-host;
    invoke-expression -Command "$command";
    };

You can then just dot source it in the terminal session

. "C:\Scripts\command.ps1";

Then you are free to call the function to type in the command to be invoked. enter image description here

PS C:\Users> command
Write-Host "My dynamic PS command invoker" -Foreground Yellow
My dynamic PS command invoker

Supporting Resource

Pimp Juice IT
  • 1,010
  • 1
  • 9
  • 16
  • Thanks for taking the time to answer, but that won't work for my use case, I need it to keep reading, but preferably blocking when there's nothing to read. – Didi Kohen Sep 04 '22 at 05:47