【发布时间】:2018-06-04 00:30:42
【问题描述】:
以下代码在 ISE 中执行时运行良好:
class MyWindow : Windows.Window {
}
# for testing purposes this is the whole script
但是在没有 ISE 的情况下运行时会导致错误:
At C:\Users\Thelonius\git\ps-scripts\minimal.ps1:1 char:18
+ class MyWindow : Windows.Window {
+ ~~~~~~~~~~~~~~
Unable to find type [Windows.Window].
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TypeNotFound
当我通过 .\minimal.ps1 在新的 Powershell 窗口中运行它时,错误是相同的。在 shell 中执行 Add-Type -AssemblyName PresentationFramework 后,.\minimal.ps1 运行没有错误。由于在解析脚本时发生错误,因此无法将Add-Type 命令添加到脚本中。据我了解,using assembly PresentationFramework 应该可以完成这项工作。但它没有(在 5.0 和 5.1 中都没有)。
那么有没有一种理智的方法可以让它在不通过 Powershell 命令行选项或类似丑陋的东西加载程序集的情况下工作?
【问题讨论】:
-
如果真的没有办法在单个文件中做到这一点,@PetSerAl 似乎是正确的。即使使用带有
powershell.exe -c "Add-Type -AssemblyName PresentationFramework; & .\minimal.ps1"之类的.lnk文件,对我来说似乎也比处理多个文件更优雅。 -
这是
Add-Type的全部内容。为什么它不完全适合你? -
@TheIncorrigible1:因为
Add-Type是在runtime执行的,对于class的定义来不及看到类型,因为它处理得比较早,在解析时间 -
@TNT:确实,
using assembly应该完成这项工作,但还没有 - 请参阅stackoverflow.com/a/51255643/45375 -
@TheIncorrigible1:你可以这样想,是的:与函数不同,类在执行开始时已经被解析;试试
[Foo]::new().Bar(); class Foo { [string] Bar() { return 'hi' } }
标签: .net powershell class