Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

class - PowerShell 5 and classes - Cannot convert the "X" value of type "X" to type "X"

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

class X
{
    [string] $A
} 

Script1.ps1

. $PSScriptRootCommon.ps1

[X] $v = New-Object X

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.

Cannot convert the "X" value of type "X" to type "X".
At D:empPSIssueScript1.ps1:3 char:1
+ [X] $v = New-Object X
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

. $PSScriptRootCommon.ps1

$v = New-Object X

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...