Hosted PowerShell cannot see Cmdlets in the same Assembly

前端 未结 3 1218
暖寄归人
暖寄归人 2020-12-17 22:21

I\'m trying to run PowerShell scripts from my C# code, that will use custom Cmdlets from the assembly that runs them. Here is the code:



        
3条回答
  •  不知归路
    2020-12-17 23:08

    The easiest way to do this with your current code snippet is like this:

    using System; 
    using System.Management.Automation; 
    
    [Cmdlet(VerbsCommon.Get,"Hello")] 
    public class GetHelloCommand:Cmdlet 
    { 
        protected override void EndProcessing() 
        { 
            WriteObject("Hello",true); 
        } 
    } 
    
    class MainClass 
    { 
        public static void Main(string[] args) 
        { 
            PowerShell powerShell=PowerShell.Create();
    
            // import commands from the current executing assembly
            powershell.AddCommand("Import-Module")
                .AddParameter("Assembly",
                      System.Reflection.Assembly.GetExecutingAssembly())
            powershell.Invoke()
            powershell.Commands.Clear()
    
            powershell.AddCommand("Get-Hello"); 
            foreach(string str in powerShell.AddCommand("Out-String").Invoke()) 
                Console.WriteLine(str); 
        } 
    } 
    

    This assumes PowerShell v2.0 (you can check in your console with $psversiontable or by the copyright date which should be 2009.) If you're on win7, you are on v2.

提交回复
热议问题