Based on my experiences, this is not possible with standard input redirection alone once the original PowerShell session has exited. Once PowerShell exits, the $p.StandardInput object is gone, and there's no built-in way to "reconnect" to that pipe from another session. But I have alternative options for you about that :
1. Option 1: Use a Script File or Command Queue
Instead of sending commands interactively via standard input, design your process to read commands from a file or queue at intervals.
- Start
cmd.exewith a loop to run commands from a file:
:loop
for /f "usebackq delims=" %%a in ("C:\Temp\command.txt") do (
if not "%%a"=="" (
%%a
)
)
timeout /t 5 >nul
goto loop
- Save that as
C:\Temp\cmd-loop.bat, and run it via PowerShell or Task Scheduler:
Start-Process -FilePath "cmd.exe" -ArgumentList "/c C:\Temp\cmd-loop.bat"
- Later, you write a command to the file from a PowerShell scheduled task:
Add-Content -Path "C:\Temp\command.txt" -Value "dir C:\`r`n"
=> This works because the process is reading and executing whatever shows up in command.txt.
2. Option 2: Use a Named Pipe, Socket, or External Listener
This involves more advanced inter-process communication (IPC), such as:
- Having the process listen on a named pipe or TCP port.
- PowerShell can then connect and send data at any time.
=> If you’re comfortable with C#, Node.js, or PowerShell remoting, this opens up many possibilities, but it's more involved.
3. Option 3: Scheduled Tasks Write to the Process via a Custom Interface
If the process you're running supports some kind of command server, like a CLI interface over TCP or pipe, then you can have it wait for commands.
For example, you could:
- Use
ncatorsocatto run a process that listens on a port. - Schedule PowerShell tasks to connect and send commands.