Created
September 30, 2022 01:28
-
-
Save romero126/e8bbebc06099f2f2e97ea17f4ae4015e to your computer and use it in GitHub Desktop.
NamedPipelines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function New-NamedPipeServer { | |
param( | |
[Parameter(Mandatory)] | |
[string] $PipeName, | |
[Parameter(Mandatory)] | |
[scriptblock] $ScriptBlock | |
) | |
Start-Job -Name $PipeName -ScriptBlock { | |
param() | |
begin { | |
# Creates the Named Pipeline | |
$PipeObject = New-Object System.IO.Pipes.NamedPipeServerStream($using:PipeName, [System.IO.Pipes.PipeDirection]::InOut); | |
$PipeReader = New-Object System.IO.StreamReader($PipeObject) | |
$PipeWriter = New-Object System.IO.StreamWriter($PipeObject) | |
} | |
process { | |
while ($true) { | |
# Wait for connection | |
$PipeObject.WaitForConnection() | |
try { | |
$PipeWriter.AutoFlush = $true | |
$ScriptBlockParameters = @{ | |
PipeReader = $PipeReader | |
PipeWriter = $PipeWriter | |
} | |
& ([scriptblock]::Create($using:ScriptBlock)) @ScriptBlockParameters | |
} | |
catch { | |
Write-Host 'An Exception was found' | |
$_ | |
} | |
finally { | |
$PipeObject.Disconnect() | |
} | |
# Only accept a single connection | |
#break | |
} | |
} | |
end { | |
Write-Host "Finishing Session" | |
$PipeReader.Dispose() | |
$PipeWriter.Dispose() | |
$PipeObject.Dispose() | |
} | |
} | |
} | |
function Connect-NamedPipe | |
{ | |
param( | |
[Parameter(Mandatory)] | |
[string] $ServerName, | |
[Parameter(Mandatory)] | |
[string] $PipeName | |
) | |
$pipeClient = [System.IO.Pipes.NamedPipeClientStream]::new( | |
$ServerName, | |
$PipeName, | |
[System.IO.Pipes.PipeDirection]::InOut | |
) | |
$pipeClient.Connect() | |
$sr = [System.IO.StreamReader]::new($pipeClient) | |
$sr.ReadToEnd() | |
$sr.Dispose() | |
$pipeClient.Dispose() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a Server | |
New-NamedPipeServer -PipeName "TestPipe" -ScriptBlock { | |
param( | |
$PipeReader, | |
$PipeWriter | |
) | |
$PipeWriter.WriteLine("I am doing something here") | |
$PipeWriter.Flush() | |
} | |
# Connect to Server and read output | |
# Read write will be more fun. | |
Connect-NamedPipe -ServerName "." -PipeName "TestPipe" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment