Handle loading of .net module into PowerShell

时间:2016-07-11 19:35:01

标签: c# powershell .net-assembly powershell-module

I have an .NET assembly that will get imported by a Powershell session using:

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.

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 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:

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.

1 个答案:

答案 0 :(得分:0)

You can implement IModuleAssemblyInitializer interface to provide module initialization code:

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