Author Posts

February 5, 2018 at 12:59 pm

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

February 5, 2018 at 7:13 pm

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.