🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Remoting Serialization

Serialization is copying an object into a plain form for travel. The other end rebuilds the object from that plain form.

An object has data and actions

A book object holds a title and a page count. It also has an action that describes it.

$book = [PSCustomObject]@{ Title = "Dune"; Pages = 412 }
$book | Add-Member -MemberType ScriptMethod -Name Describe -Value { "Title is Dune" }
$book.Title
$book.Describe()

A round trip keeps the data

Saving the object to a file and reading it back rebuilds it. The title and page count survive the trip.

$book = [PSCustomObject]@{ Title = "Dune"; Pages = 412 }
$book | Export-Clixml -Path "book.xml"
$back = Import-Clixml -Path "book.xml"
$back.Title
$back.Pages

A round trip loses the action

The rebuilt object keeps its data but not its actions. Calling the old action fails with a real message.

$book = [PSCustomObject]@{ Title = "Dune"; Pages = 412 }
$book | Add-Member -MemberType ScriptMethod -Name Describe -Value { "Title is Dune" }
$book | Export-Clixml -Path "book.xml"
$back = Import-Clixml -Path "book.xml"
try {
  $back.Describe()
} catch {
  "Caught: " + $_.Exception.Message
}

Example

$book = [PSCustomObject]@{ Title = "Dune"; Pages = 412 }
$book | Add-Member -MemberType ScriptMethod -Name Describe -Value { "Title is Dune" }
$book | Export-Clixml -Path "book.xml"
$back = Import-Clixml -Path "book.xml"
$back.Title
$back.Pages
$back.PSObject.TypeNames[0]
try {
  $back.Describe()
} catch {
  "Caught: " + $_.Exception.Message
}

Key points

  • Serialization: copying an object into a plain form for travel.
  • Deserialized object: the rebuilt copy at the other end.
  • Properties survive: the data fields of the object arrive intact.
  • Methods do not survive: the actions of the object are lost in travel.
  • Property use: read fields from a returned object, and do not call its old actions.

In this example, a book object is built with data and one action. A file round trip rebuilds it, and the title and page count print unchanged. The rebuilt type name starts with Deserialized, and calling the old action fails with a real message.

Note

On this machine, a local Invoke-Command run does not rebuild the object, so this lesson proves the rebuild step with a file round trip instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What survives when an object travels through serialization?