Issue with multiple class declarations


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

class TestClass {
[string] $VeryNice = “This looks good!”

[void] PrintMe() {
	Write-Host $this.VeryNice


. .\Evil.ps1

$Object = [TestClass]::new()

GiveItToMe $Object

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: (:slight_smile: [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?

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.