powershell自动加载所有.NET命名空间


PowerShell交流中心分类: Powershell基础powershell自动加载所有.NET命名空间
0
leopard asked 9 年 ago

如何配置powershell使powershell启动时自动加载所有的.NET的类库,而不必每次新建.NET对象时,都要先用Add-Type载入相关的命名空间?
例如:
Add-Type -AssemblyName mscorlib
$str = New-Object System.Text.StringBuilder
$str.Append(“Hello”)
$str.ToString()
如何编辑powershell的配置文件?

2 Answers
1
Best Answer
Mooser Lee 管理员 answered 9 年 ago

首先你确定你要这样做?一次性将所有的.NET 程序集都添加引用进来,而其中可能只有几个常用的才会被经常用到。一定会遇到性能问题。
所有的程序集都位于:

dir "$env:windir\Microsoft.Net\assembly" -Recurse

推荐的方法:
把你要加载的程序集放在profile文件中,这样每次打开PowerShell,这些脚本会被自动执行,你可以把Add-Type的逻辑放在里面。
可以参考:Windows PowerShell Profile配置文件

leopard replied 9 年 ago

非常感谢您,确实不必全部加载。

0
J answered 9 年 ago
PS > [AppDomain]::CurrentDomain.GetAssemblies() | select FullName

可以看到常用的 BCL 基本都载入啦


leopard replied 9 年 ago

Cool!