Custom types with invoke-command

This topic contains 1 reply, has 2 voices, and was last updated by  Don Jones 3 months, 2 weeks ago.

  • Author
    Posts
  • #92962

    Aurimas N.
    Participant

    Hi,
    I'm trying to construct custom type via invoke-command, and then use that info locally, however I can't figure out how to bring the data back from remote session as my custom type.

    locally I have this:

    class PropertyClass
    {
        [string]$PropertyClassProp1
        PropertyClass()
        {
            $this.PropertyClassProp1 = "anything"
        }
    }
    
    class MyClass
    {
        [string]$MyClassProp1
        [PropertyClass]$MyClassProp2
    
        MyClass()
        {
            $this.MyClassProp1 = "prop of myclass"
            $this.MyClassProp2 = [PropertyClass]::new()
        }
    }
    
    $Locally = [MyClass]::new()
    $Locally.MyClassProp2
    PS C:\Windows\system32> $Locally.MyClassProp2
    
    PropertyClassProp1
    ------------------
    anything          
    

    I'm trying to do the same with invoke-command

    $types = @'
    class PropertyClass
    {
        [string]$PropertyClassProp1
        PropertyClass()
        {
            $this.PropertyClassProp1 = "anything"
        }
    }
    
    class MyClass
    {
        [string]$MyClassProp1
        [PropertyClass]$MyClassProp2
    
        MyClass()
        {
            $this.MyClassProp1 = "prop of myclass"
            $this.MyClassProp2 = [PropertyClass]::new()
        }
    }
    '@
    $Remotely = Invoke-Command -ComputerName localhost -ScriptBlock {Invoke-Expression $using:types
    $rem = [MyClass]::new()
    return $rem
    }
    $Remotely.MyClassProp2

    in the remote session everything is being run as expected, but once I try to save the data locally my types are lost:

    PS C:\Windows\system32> $Remotely.MyClassProp2
    PropertyClass
  • #93028

    Don Jones
    Keymaster

    You won't be able to in the current implementation of classes in PowerShell. The underlying serialization/deserialization doesn't work for this; classes in PowerShell aren't "first class citizens" at this stage.

You must be logged in to reply to this topic.