PowerShell 5 and classes – Cannot convert the “X” value of type “X” to type “X”

Question:

I’m trying to use PowerShell’s classes that is very handy way of grouping related data together and facing quite tedious to deal with behavior. The simplified scenario: one PS script that defines class and another script that uses that class.

Common.ps1

Script1.ps1

Everything is good – you can run Script1.ps1 arbitrary amount of times with no issues – until you make any change in Common.ps1. You will face the following error.

Conceivably any change (even if you just added whitespace) in PS file forces its recompilation, so that type X becomes different than X it used to be – temporary container assembly has been changed (the very same issue easily reproducible in .NET – types are identical as long as “Fully Qualified Assembly Names” are the same). Change in Script1.ps1 makes things function normally again.

Is there any way to overcome such kind of issues?

Answer:

I was able to replicate and resolve your issue. It is similar to if you define a class in a scope and you try to define another class in the same scope. The class definition is retained in PowerShell session. In Script1.ps1 you need to modify the code to not explicitly declare the variable to type. Just use as below to not use Strong Typing and let PowerShell determine the type and assign it dynamically:

Now you should be able to change the definition of class X in Common.ps1 as many times as you want without needing to close and reload.

The example above uses “Weak typing” You can read more about this and other details here: Variable Types and Strongly Typing

Source:

PowerShell 5 and classes – Cannot convert the “X” value of type “X” to type “X” by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply