vendredi 25 mai 2018

Using external code in PowerShell classes

In my PowerShell script I try to access functions from external .NET DLLs. The example is about Aspose.NET which is a utility for office automation and offers access to various fileformats.

Most of the code examples are about high-level compiled .NET languages but I want to use it with PowerShell.

My observation is the following:

$AsposeDll = New-Object "System.IO.FileInfo" ".\Aspose.Pdf.dll"
Add-Type -Path $AsposeDll.FullName
[Reflection.Assembly]::LoadFile($AsposeDll.FullName)

this executes flawlessly and prints out the version of the file and I assume it is loaded by then.

If I put the following in the global space

[Aspose.Pdf.License]$Lic = New-Object "Aspose.Pdf.License"

It also executes fine. If I put the same command into a top-level function like:

function Test
{
    [Aspose.Pdf.License]$Lic = New-Object "Aspose.Pdf.License"
}
Test

It will cause no problems.

But if I write down in a class (It's PowerShell 5.0)

class PdfProvider
{
    [bool]$Loaded
    [Aspose.Pdf.License]$Lic
}

It won't execute because it tells me the type could not be found. Even commands that stand in the code before the class "should get read" are not executed, so my guess is that it screens preemptive to look if there could be an illegal execution (without loading the DLL) happening.

Is there a way you can use external code in your classes in PowerShell or is it forbidden to do so?





Aucun commentaire:

Enregistrer un commentaire