PowerShell Module IModuleAssemblyInitializer OnImport() - Is it possible to find out with which parameters the module is loaded?

Stefan Soller 6 Reputation points
2021-02-02T13:39:41.847+00:00

Hi All,

Is it possible to find out if my PowerShell assembly is being imported with the -Prefix parameter?

PowerShell call:
Import-Module "C:\Temp\Test.dll" -Prefix

And then in my C# code:

namespace PowerShell_Module
{
    public class MyModuleAssemblyInitializer : IModuleAssemblyInitializer
    {
        public void OnImport()
        {
            // Check for switch parameter

        }
    }
}

Or is it generally possible to find out what the command of the call looks like?

Many thanks for your help

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,408 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2021-02-03T07:49:30.597+00:00

    I don't know much about powershell, but I saw this in the documentation:
    Command.Parameters Property
    Please try it in the code:

            public void OnImport()  
            {  
                using (PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace))  
                {  
                    PSCommand pSCommand = ps.Commands;  
                    foreach (var item in pSCommand.Commands)  
                    {  
                        CommandParameterCollection commandParameters =  item.Parameters;  
                        foreach (var paras in commandParameters)  
                        {  
                            var param = paras.Name;  
                        }  
                    }  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.