Using .NET objects within a Powershell (V5) class

Question:

Below is the exact code that I am having trouble with.

A brief description:

I am trying to set up a PowerShell class that will hold objects of different types for easy access. I’ve done this numerous times in C#, so I thought it would be fairly straight forward. The types wanted are [System.Printing] and WMI-Objects.

Originally I had tried to write the class directly to my PowerShell profile for easy usage, but my profile fails to load when I have to class code in it. Saying that it can’t find the type name “System.Printing.PrintServer”, or any other explicitly listed types.

After that failed, I moved it to its own specific module and then set my profile to import the module on open. However, even when stored in its own module, if I explicitly list a .NET type for any of the properties, the entire module fails to load. Regardless of whether I have added or imported the type / dll.

The specific problem area is this:

When I have it set to this, everything “kind of” works, but then all my properties have the _Object type, which is not helpful.

Answer:

Every PowerShell script is completely parsed before the first statement in the script is executed. An unresolvable type name token inside a class definition is considered a parse error. To solve your problem, you have to load your types before the class definition is parsed, so the class definition has to be in a separate file. For example:

Main.ps1:


Class.ps1:

The other possibility would be embed Class.ps1 as a string and use Invoke-Expression to execute it. This will delay parsing of class definition to time where types is available.

Source:

Using .NET objects within a Powershell (V5) class by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply