Issue with multiple class declarations

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 6 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36702
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    Howdy

    If you have these two files in the same folder (and PowerShell5 installed):
    Test.ps1

    class TestClass {
    	[string] $VeryNice = "This looks good!"
    	
    	[void] PrintMe() {
    		Write-Host $this.VeryNice
    	}
    }
    
    . .\Evil.ps1
    
    $Object = [TestClass]::new()
    $Object.PrintMe()
    
    GiveItToMe $Object

    Evil.ps1

    class TestClass {
    	[string] $MyEvil = "Very bad!"
    	
    	[void] PrintMe() {
    		Write-Host $this.MyEvil
    	}
    }
    
    function GiveItToMe([TestClass] $Object) {
    	Write-Host $Object.ToString()
    }

    And then run Test.ps1 you will get the following output and error:
    This looks good!
    GiveItToMe : Cannot process argument transformation on parameter 'Object'. Cannot convert the "TestClass" value of type "TestClass" to type "TestClass".
    At C:\temp\Test.ps1:14 char:12
    + GiveItToMe $Object
    + ~~~~~~~
    + CategoryInfo : InvalidData: (:) [GiveItToMe], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,GiveItToMe

    I received this error in a much larger collection of scripts and it was horrible. It kind of says that you can't convert a TestClass to itself, which makes no sense.

    The problem is that TestClass isn't TestClass here and this wouldn't be allowed if you put the content of Evil.ps1 into Test.ps1 (It will give an "The member 'TestClass' is already defined" error).

    My first question is: Why can you declare the same class multiple times?

    I came across this issue when creating a script with classes, ran the script, modified the script and ran it once more, etc. I guess I had multiple definitions of the class in my environment/in memory and I ran into many weird errors.

    So my second question is: How can I prevent this from happening? Is it possible to somehow get a clean environment every time you run a script without restarting powershell.exe/powershell_ise.exe?

    #37006
    Profile photo of Don Jones
    Don Jones
    Keymaster

    you might just be running into the fact that classes are still new and a little rough around the edges. But no, the ISE would require a restart to get a clean new scope – that's how it's designed.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.