I am adding this type and calling it. It works fine in script/function. As soon as I am trying to call it from powershell class - it gives error "type is not defined".
I have managed to call it using some ugly hacks. Add-Type
is called with -PassThru
and result is saved in $global:myType
. Then I am doing indirect call using $global:myType.GetMethod('GetSymbolicLinkTarget').invoke($null,$dir)
.
Is there any better solution around?
PS: runspace is reset before each run (Ctrl-T in ISE, automatic in PowerGUI and Powershell Studio).
PS2: Working sample (simplified) below.
#works - returns 2
$Source = ' public class BasicTest { public static int Test(int a) { return (a + 1); } } '
Add-Type -TypeDefinition $Source
[BasicTest]::Test(1)
#gives error: Unable to find type [BasicTest]
$Source = ' public class BasicTest { public static int Test(int a) { return (a + 1); } } '
Add-Type -TypeDefinition $Source
class foo { Static [int]bar() { return [BasicTest]::Test(1) } }
[foo]::bar()
#workaround 1 - indirect call with GetMethod(...).Invoke(...)
# returns 4
$Source = ' public class BasicTest1 { public static int Test(int a) { return (a + 1); } } '
$global:BasicTestType1 = (Add-Type -TypeDefinition $Source -PassThru)
class foo {
static $BasicTestType2 = (Add-Type -TypeDefinition ' public class BasicTest2 { public static int Test(int a) { return (a + 1); } } ' -PassThru)
Static [int]bar() {
$ret = $global:BasicTestType1.GetMethod('Test').Invoke($null, [int]1)
$ret += [foo]::BasicTestType2.GetMethod('Test').Invoke($null, [int]1)
return $ret
}
}
[foo]::bar()
#workaround 2 - invoke-expression; has problems passing parameters
# returns 2
$Source = ' public class BasicTest { public static int Test(int a) { return (a + 1); } } '
Add-Type -TypeDefinition $Source
class foo { Static [int]bar() { return invoke-expression '[BasicTest]::Test(1)' } }
[foo]::bar()
PS3: Two other workarounds are provided here by PetSerAl.