Powershell

I had a bit of an obscure need recently at work to create a named pipe. This is usually a developer thing to do, but in order to perform some testing in our lab, we needed to produce systems that matched a certain criteria, and one of those was to have a named pipe with a certain name.

Turns out that it’s not hard to create named pipes in PowerShell, with one caveat. You must have .NET 3.5 installed on a system in order to do it. It can be done without this newer version of .NET, but the work required is more and I didn’t have the time to figure out that method.

As PowerShell is made with .NET 2.0, the 3.5 namespace that we need isn’t loaded by default. To remedy that is one line:

PS > [reflection.Assembly]::LoadWithPartialName("system.core")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\WINDOWS\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\Sys...

Or if you are using PowerShell v2:

PS > Add-Type -AssemblyName system.core

Once you’ve done that, creating the pipe is just one more line:

PS > $pipe = New-Object system.IO.Pipes.NamedPipeServerStream("Bob")
PS > $pipe

IsConnected       : False
IsAsync           : False
IsMessageComplete :
TransmissionMode  : Byte
InBufferSize      : 0
OutBufferSize     : 0
ReadMode          : Byte
SafePipeHandle    : Microsoft.Win32.SafeHandles.SafePipeHandle
CanRead           : True
CanWrite          : True
CanSeek           : False
Length            :
Position          :
CanTimeout        : False
ReadTimeout       :
WriteTimeout      :

Many thanks to Joel & Oisin for pointing out this .NET namespace and pointing out that I had to load system.core.

: http://halr9000.com/article/702

2009-02-27 11:05:23

If you’re want to be safe and specific, use the full strong/versioned name when you load it (so sez Oisin):

[Reflection.Assembly]::Load(“System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″)

2009-02-27 11:08:32

Actually, you can do that with Add-Type, too …

Add-Type -Assembly “System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″

The current version of Add-Type is hard-coded to map “System.Core” to that version of the dll anyway, but who can say if that will change with some future version of PowerShell?

2009-03-01 15:54:59

What I don’t get is why it echos/displays info regarding “v2.0.50727″ in the version property? I guess I’m wrongfully assuming that this version property is related to the library/.NET version being loaded.

  • Microblog

  • Recent Posts

  • Recent Comments

  • meta

  • PowerShell Blogroll