Search code examples
powershellpowercli

Why is PowerShell's calling function not receiving the proper object type?


I am using VMware PowerCLI to perform some stuff with virtual machines in a PowerShell module with PowerShell 7.1.3. I am seeing some weird behavior with object types. Here's a rundown of what I'm doing:

Parent-Function.ps1:

function Parent-Function {
    $osCustomizationSpec = Child-Function -Name "AUTODEPLOY-ExampleConfiguration"
    Write-Verbose -Message $osCustomizationSpec.GetType()
}

This prints System.Object[] to the verbose stream

Child-Function.ps1:

function Child-Function {
    param([Parameter][string]$Name)

    $osCustomizationSpec = Get-OSCustomizationSpec -Name $Name
    Write-Verbose -Message $osCustomizationSpec.GetType()
    return $osCustomizationSpec
}

This prints VMware.VimAutomation.ViCore.Impl.V1.VIObjectImpl to the verbose stream

Basically, why is the calling function receiving the object as an array of System.Objects, when it's supposed to be returned as a VMware.VimAutomation.ViCore.Impl.V1.VIObjectImpl object?


Solution

  • Because PowerShell returns all output. You’re returning .GetType() then a return. PowerShell will collect that in an an array.

    If you return 1 object you’ll get a scalar value of the given type. Return more than 1 object and you’ll get an array.

    If those .GetType() calls are for debugging. Front them with Write-Host like:

    Write-Host ( $osCustomizationSpec).GetType().FullName

    That will write to the console not the output stream.