Reputation: 305
I'm having a hard time piping data from a PowerShell script into a C# program.
Thanks to this answer I was given, I've come up with a working solution for piping data between two PowerShell scripts(Sender.ps1
and Receiver.ps1
).
The problem is, this script doesn't work when translated into C# code.
Even if I invoke Receiver.ps1
in C# via the PowerShell
class, it still doesn't work.
This answer to a similar question leads me to believe that the namespace for the pipes isn't the same, but when I tried adding Global
to the beginning of each pipe it didn't do anything. Again, it works in the two .ps1
's if I run as PowerShell scripts, but if I invoke one of the scripts from C#, or translate it directly into C#, it stops working altogether.
Does anyone know anything about namespaces and pipelining in Windows?
Sender.ps1: doesn't interact with C# program, other than sending data through the pipe
## Establish Pipe
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream("Global\\.pipe\brokenPipe");
$pipe.Connect();
$stream = New-Object System.IO.StreamWriter($pipe);
## Communicate through Pipe
SendStuff();
## Close Pipe
$stream.Dispose();
$pipe.Dispose();
Receiver.ps1: PowerShell program for reading from the pipe. Works if I right-click and run as PowerShell. Doesn't work if I invoke it via C#'s PowerShell, it just hangs at WaitForConnection()
. The C# program is invoking the script correctly, I tested this with a dummy file full of information (which was read by C# correctly). For some reason, the pipe stops working when it's run via my C# Application
## Establish Pipe
$pipe = new-object System.IO.Pipes.NamedPipeServerStream("Global\\.pipe\brokenPipe");
$pipe.WaitForConnection();
$stream = new-object System.IO.StreamReader($pipe);
## Communicate through Pipe
ReadStuff();
## Close Pipe
$stream.Dispose();
$pipe.Dispose();
C# Receiver Function: I made this as a substitute to PowerShell.Create()
, and this doesn't work either (even though it's the exact same code as Receiver.ps1
.
void PipeListener(){
## Establish Pipe
var pipe = new System.IO.Pipes.NamedPipeServerStream("Global\\.pipe\brokenPipe");
pipe.WaitForConnection();
var stream = new System.IO.StreamReader(pipe);
## Communicate through Pipe
ReadStuff();
## Close Pipe
stream.Dispose();
pipe.Dispose();
}
Upvotes: 2
Views: 784
Reputation: 22281
The global namespace prefix is Global\
, not Global\\
. You do not need to escape the backslash in Powershell.
Global\pipename
@"Global\pipename"
or "Global\\pipename"
Upvotes: 2