【发布时间】:2017-02-11 20:39:25
【问题描述】:
我正在添加这个type 并调用它。它在脚本/函数中运行良好。一旦我试图从 powershell 类中调用它 - 它会给出错误“类型未定义”。
我已经设法使用一些丑陋的黑客来称呼它。 Add-Type 用-PassThru 调用,结果保存在$global:myType 中。然后我使用$global:myType.GetMethod('GetSymbolicLinkTarget').invoke($null,$dir)进行间接调用。
有没有更好的解决方案?
PS:每次运行前都会重置运行空间(ISE 中为 Ctrl-T,PowerGUI 和 Powershell Studio 中为自动)。
PS2:工作示例(简化)如下。
#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:PetSerAl 提供了另外两个解决方法here。
【问题讨论】:
-
您是否已经尝试过他们在链接代码 sn-p 末尾所做的方式?
[System.Win32]::GetSymbolicLinkTarget($dir)这是公认的答案,OP说它有效...... -
Add-Type <...>; class foo { Static [void]bar() { [System.Win32]::GetSymbolicLinkTarget('c:\') } }- 它甚至无法编译。 PS:每次运行前都会重置运行空间。 -
在静态方法中移动
Add-Type也无济于事。 -
Invoke-Expression 'here go code using the added type' 可能吗?
-
您能否提供示例类型以及您如何重置运行空间以及何时重置?
标签: class powershell