0

I have a Powershell module ExportHelper.psm1 in which I define a custom class Text and a function Add-Text:

class Text {
  [string]$value
  [Format]$format
}

function Add-Text {
  Param([Text]$text)
  echo $text.value
}

It is important to me that the Add-Text function takes a parameter of type Text as I want to use specific properties of this class and it wouldn't be appropriate for someone to call the function with a string parameter.

If I call the Add-Text function from within ExportHelper.psm1 then I see the expected result:

$testText = [Text]@{
    value = "Test text"
    format = ([Format]::Heading1)
}
Add-Text -text $testText

Outputs:
Test text

If I call the Add-Text function from a separate powershell script Playings.ps1 with exactly the same $testText variable constructed in exactly the same way, I instead get an error:

Cannot process argument transformation on parameter 'text'. Cannot convert the "Text" value of type "Text" to type "Text".

If I try echo $testText.GetType().Name then I see $testText is correctly created as a Text object.

I always Import-Module and Remove-Module at each end of my script to make sure I'm using the latest version of ExportHelper.psm1 and indeed I see changes if I modify the Add-Text function.

So my question is: why does Powershell not understand that the $testText variable defined in Playings.ps1 is already of the same type as required by Add-Text? Why does this error only occur when calling the function from outside the module?

3
  • Shouldn't the type be string and not the class TEXT. Commented May 5, 2023 at 12:15
  • What is [Format] ? Commented May 5, 2023 at 13:44
  • Text and Format are two custom classes I have defined within ExportHelper.psm1 Commented May 10, 2023 at 8:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.