2

Consider snippet below

$JobResult = Start-Job -ScriptBlock {
    $Result = @("foo", "bar")
    Write-Host "Returning type $($Result.GetType().Name)"
    $Result
} | Receive-Job -Wait -AutoRemoveJob
Write-Host "Returned type $($JobResult.GetType().Name)"

It prints as expected

Returning type Object[]
Returned type Object[]

But when more complex object is needed on return, e.g.:

$JobResult = Start-Job -ScriptBlock {
    $Result = @{ InnerArray = @("foo", "bar") }
    Write-Host "Returning type $($Result.InnerArray.GetType().Name)"
    $Result
} | Receive-Job -Wait -AutoRemoveJob
Write-Host "Returned type $($JobResult.InnerArray.GetType().Name)"

Prints

Returning type Object[]
Returned type ArrayList

We have stumbled upon this when writing unit tests for some function we have for dealing with jobs and verification wasn't happy because it got different types. Why is it happening? And is there any documentation why?

Furthermore even the PowersHell's automatic array unwrapping is inconsistent here (at least from my perspective). In first snippet if only one string is present in an array, result type is String. But in second snippet, it "remains" ArrayList.

Tested on PSVersion 5.1.17763.1971

pavel1269
  • 21
  • 2
  • 1
    See [Serialization of variable values](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_variables#serialization-of-variable-values): "*For a limited set of types, deserialization rehydrates objects back to the original type. The rehydrated object is a copy of the original object instance. It has the type properties and methods. For simple types, such as `System.Version`, the copy is exact. For complex types, the copy is imperfect. For example, rehydrated certificate objects do not include the private key.*" – iRon Aug 04 '21 at 17:26

0 Answers0