Pipelining between two SEPARATE Powershell processes

一笑奈何 提交于 2019-12-20 02:56:26

问题


Let's say I have two PowerShell programs running: Producer.ps1 and Consumer.ps1.

Is there any way to establish a client-server relationship between the two .ps1 files I have?

Specifically, Producer.ps1 outputs a PSObject containing login info. Is there any way I can establish a listener and named pipe between the two objects to pass this PSObject from Producer.ps1 directly into Consumer.ps1?


(Note: the two files cannot be combined, because they each need to run as different Windows users. I know one possible solution for communicating is to write the PSObject to a text/xml file, then have the client read and erase the file, but I'd rather not do this since it exposes the credentials. I'm open to whatever suggestions you have)


回答1:


I found this link that describes how to do what you're requesting: https://gbegerow.wordpress.com/2012/04/09/interprocess-communication-in-powershell/

I tested it and I was able to pass data between two separate Powershell sessions.

Server Side:

$pipe=new-object System.IO.Pipes.NamedPipeServerStream("\\.\pipe\Wulf");
'Created server side of "\\.\pipe\Wulf"'
$pipe.WaitForConnection(); 

$sr = new-object System.IO.StreamReader($pipe); 
while (($cmd= $sr.ReadLine()) -ne 'exit') 
{
 $cmd
}; 

$sr.Dispose();
$pipe.Dispose();

Client Side:

$pipe = new-object System.IO.Pipes.NamedPipeClientStream("\\.\pipe\Wulf");
 $pipe.Connect(); 

$sw = new-object System.IO.StreamWriter($pipe);
$sw.WriteLine("Go"); 
$sw.WriteLine("start abc 123"); 
$sw.WriteLine('exit'); 

$sw.Dispose(); 
$pipe.Dispose();


来源:https://stackoverflow.com/questions/32056955/pipelining-between-two-separate-powershell-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!