0

I have a generic module MyModule.psm1 which creates and returns any custom type provided:

function Create-CustomType {
    param (
        [Parameter(Mandatory)]
        [System.Reflection.TypeInfo] $CustomType
    )
    // Some irrelevant logic ..................................................//
    
    return New-Object -TypeName $CustomType.FullName -Property $objectProperties
}

Also, I have some custom types, defined in the separate file types.ps1:

class User{
    // Some properties
}

Last, but not least I have a RunMyLogic.ps1 script, which looks like that:

Import-Module -Name "$pathToMyCustomModulesFolder\\MyModule.psm1"
. ($PSScriptRoot + '\types.ps1')
# New-Object -TypeName $CustomType.FullName -Property $objectProperties
Create-CustomType -CustomType ([User])

The problem is that when I run RunMyLogic.ps1, my Create-CustomType function fails with the message Cannot find type [User]: verify that the assembly containing this type is loaded.

If I create a User directly in RunMyLogic.ps1 then it works just fine (see commented line). But when I pass it to the MyModule.psm1 it fails. Please, help to figure out what's wrong with it

managerger
  • 728
  • 1
  • 10
  • 31
  • The custom type can't be resolved by name from within the module. Change the parameter type to `[System.Type]` and use `$CustomType::new()` instead of `New-Object`. – Mathias R. Jessen Oct 08 '20 at 16:46
  • @MathiasR.Jessen That might work, but I have $objectProperties with values. And I don't see an easy way to initialize all these properties if I use #type::new() – managerger Oct 08 '20 at 16:57
  • Is `$objectProperties` a dictionary? `$objectProperties -as $CustomType` – Mathias R. Jessen Oct 08 '20 at 16:58
  • @MathiasR.Jessen Yes, it is a hashset with actual values – managerger Oct 08 '20 at 17:00
  • 1
    It won't work with a hashset, but if it's a hashtable (which is also a kind of dictionary), then `-as [type]` will work – Mathias R. Jessen Oct 08 '20 at 17:05
  • @MathiasR.Jessen I didn't really expect to get the help so quickly, thank you, sir, very much! I was looking through the Internat/reading/googling and I haven't seen anything like `custom type can't be resolved by name from within the module`? But it explains everything, except the Why question))) If you can share an article or reference to docs, where I can read more details I will appreciate it – managerger Oct 08 '20 at 17:25

0 Answers0