title: Returning .NET objects in PowerShell functions
body: <p>I'm trying to get the script below working. The problem I keep running into is the Object being returned is a SystemObject[] instead of a PdfSharp.Pdf.PdfDocument.</p>
  <p>I wrote the below script with the idea of using this in a larger script by setting a <code>$out = New-Object PdfSharp.Pdf.PdfDocument</code> and capturing the return. Unfortunately, this did not work.</p>
  <p>After googling for several hours, and finding nothing, I am open to suggestions.</p>
  <pre><code>Add-Type -Path C:\assemblies\GDI+\PdfSharp.dll
  
  Function mergePdf {
      Param($file1, $file2)
  
      $output = New-Object PdfSharp.Pdf.PdfDocument
      $PdfReader = [PdfSharp.PDF.IO.PdfReader]
      $PdfDocumentOpenMode = [PdfSharp.Pdf.IO.PdfDocumentOpenMode]
  
  
      $input = New-Object PdfSharp.Pdf.PdfDocument
      $input = $PdfReader::Open($file1, $PdfDocumentOpenMode::Import)
      $input.Pages | %{$output.AddPage($_)}
      $input = $PdfReader::Open($file2, $PdfDocumentOpenMode::Import)
      $input.Pages | %{$output.AddPage($_)}
  
      return $output
  }
  </code></pre>
  <p>Edit: I changed <code>$output.pages</code> to the previous <code>$output</code> for clarity, but the script still fails to pass a PdfSharp.Pdf.Pdfdocument object back from the function correctly.</p>
  <pre class="lang-none prettyprint-override"><code>$obj = mergePdf temp1.pdf temp2.pdf
  $obj.Save(&quot;./merged/temp.pdf&quot;)
  Method invocation failed because [System.Object[]] doesn't contain a method named 'Save'
  .  At line:1 char:10
  + $obj.Save &lt;&lt;&lt;&lt; (&quot;./merged/temp.pdf&quot;)
  + CategoryInfo          : InvalidOperation: (Save:String) [], RuntimeException
  + FullyQualifiedErrorId : MethodNotFound
  </code></pre>
  <p>And yet I get:</p>
  <pre class="lang-none prettyprint-override"><code>$obj | gm
  TypeName: PdfSharp.Pdf.PdfDocument
  
  Name              MemberType Definition
  ----              ---------- ----------
  AddPage           Method     PdfSharp.Pdf.PdfPage AddPage(), PdfSharp.Pdf.PdfPage Add...
  ...
  Save              Method     System.Void Save(string path), System.Void Save(System.I...
  </code></pre>