[英]Handle loading of .net module into PowerShell
I have an .NET assembly that will get imported by a Powershell session using:我有一个 .NET 程序集,它将使用 Powershell 会话导入:
Import-Module MyAssemblyFirst.dll
What I need is to automatically load another custom assembly ( MyAssemblySecond.dll
) that I know about when MyAssemblyFirst.dll
gets imported.我需要的是自动加载另一个自定义程序集(
MyAssemblySecond.dll
),我知道何时导入MyAssemblyFirst.dll
。
The scenario I am looking for is:我正在寻找的场景是:
Import-Module MyAssemblyFirst.dll
Import-Module MyAssemblySecond.dll
but I would rather like to have only one Import-Module
call:但我宁愿只有一个
Import-Module
调用:
Import-Module MyAssemblyFirst.dll
...and somehow to trigger loading the second assembly as well. ...并以某种方式触发加载第二个程序集。
The 2 assemblies do not reference each other but I am the owner of both.这两个程序集不相互引用,但我是两者的所有者。 I'm just trying to simplify importing multiple assemblies by importing only one.
我只是想通过只导入一个来简化导入多个程序集。
So in a broader example, I am looking to simplify a PS script like this:因此,在更广泛的示例中,我希望简化这样的 PS 脚本:
Import-Module MyAssemblyFirst.dll
Import-Module MyAssemblySecond.dll
Import-Module MyAssemblyThird.dll
... ...
Import-Module MyAssemblyNth.dll
to a single line:到一行:
Import-Module MyAssemblyFirst.dll
EDIT: The purpose for this is that based on a certain logic located in MyAssemblyFirst.dll I might want to automatically import some other assemblies that expose some new specific PS commands.编辑:这样做的目的是基于位于 MyAssemblyFirst.dll 中的某个逻辑,我可能想要自动导入一些其他公开一些新的特定 PS 命令的程序集。
You can implement IModuleAssemblyInitializer
interface to provide module initialization code:您可以实现
IModuleAssemblyInitializer
接口以提供模块初始化代码:
Add-Type -TypeDefinition @‘
using System;
using System.Management.Automation;
[Cmdlet(VerbsLifecycle.Invoke, "Command1")]
public class Command1 : Cmdlet {
protected override void ProcessRecord() {
WriteObject("Command 1");
}
}
public class ModuleInitializer : IModuleAssemblyInitializer {
public void OnImport() {
using(PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) {
ps.AddCommand("Write-Host").AddArgument("Before submodule import").AddStatement().
AddCommand("Import-Module").AddArgument(".\\Assembly2.dll").AddStatement().
AddCommand("Write-Host").AddArgument("After submodule import").Invoke();
}
}
}
’@ -OutputAssembly .\Assembly1.dll
Add-Type -TypeDefinition @‘
using System;
using System.Management.Automation;
[Cmdlet(VerbsLifecycle.Invoke, "Command2")]
public class Command2 : Cmdlet {
protected override void ProcessRecord() {
WriteObject("Command 2");
}
}
public class ModuleInitializer : IModuleAssemblyInitializer {
public void OnImport() {
using(PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) {
ps.AddCommand("Write-Host").AddArgument("Importing submodule").Invoke();
}
}
}
’@ -OutputAssembly .\Assembly2.dll
Write-Host 'Before module import'
Import-Module .\Assembly1.dll
Write-Host 'After module import'
Invoke-Command2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.