Search code examples
powershellpowershell-4.0type-accelerators

Why can I not cast to [PSSession] declaring function parameters?


I cannot figure out how to cast a PSSession correctly for use as a parameter in a function.

Do I have to load an assembly or something? I'm using Powershell v4.

I like to cast my functions parameters to make sure of correct usage. What I'm trying is:

function Some-Remote-Task([PSSession] $Session, [String]$Target) {
  # Do stuff...
}

But I get this error while casting my Parameter:

Unable to find type [PSSession]. Make sure that the assembly that contains this type is loaded.

Also, using $mySession.GetType() on a valid session yields the following:

IsPublic IsSerial Name                                     BaseType                                                                                                                           
-------- -------- ----                                     --------                                                                                                                           
True     False    PSSession                                System.Object    

So it seems like that should be the right type name...

All help is appreciated.


Solution

  • EDIT:

    I can now use [PSSession] properly.

    By combining information from the link in biantist's comment: Type Accelerator

    With another answer here: Simplify Your Script...

    I added the Type Accelerator properly:

    PS c:\> [PowerShell].Assembly.GetType("System.Management.Automation.TypeAccelerators")::add(“PSSession”,”System.Management.Automation.Runspaces.PSSession”)
    
    PS c:\> [PSSession]
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     False    PSSession                                System.Object
    

    WAS:

    In the end I used an alias. Posted for others who also prefer a clean look.

    New-Alias PSSession System.Management.Automation.Runspaces.PSSession
    

    -ErrorAction SilentlyContinue Is useful to add to it during testing if you keep rerunning the same code segments.