Search code examples
powershellautocadpowershell-4.0autocad-plugin

Are these function definitions not the same?


PowerShell 4.0

It works fine:

$cad  = [Autodesk.AutoCAD.ApplicationServices.Application]
function Get-DocumentManager { $cad::DocumentManager }
function Get-CurrentDocument { $cad::DocumentManager.MdiActiveDocument }
function Get-CurrentEditor { (Get-CurrentDocument).Editor }
function Get-CurrentDatabase { (Get-CurrentDocument).Database }

All these functions return the necessary objects. But if I rewrite the body of Get-CurrentDocument function then I get the problem:

$cad  = [Autodesk.AutoCAD.ApplicationServices.Application]
function Get-DocumentManager { $cad::DocumentManager }
function Get-CurrentDocument { (Get-DocumentManager).MdiActiveDocument }
function Get-CurrentEditor { (Get-CurrentDocument).Editor }
function Get-CurrentDatabase { (Get-CurrentDocument).Database }

I get the error message when I launch the Get-CurrentDocument function:

Object reference not set to an instance of an object.

Why does it happen? This way works fine for my Get-CurrentEditor and Get-CurrentDatabase functions.


Solution

  • Possible reason for such difference is PowerShell behavior of unrolling collections. If $cad::DocumentManager is collection, then Get-DocumentManager will return not collection itself, but collection's elements. To prevent this, you need to use unary array operator ,. It create array with single element. And that array will be unrolled instead of collection.

    function Get-DocumentManager { ,$cad::DocumentManager }