Calling Powershell functions from C#

后端 未结 2 616
悲哀的现实
悲哀的现实 2020-12-09 10:54

I have a PS1 file with multiple Powershell functions in it. I need to create a static DLL that reads all the functions and their definitions in memory. It then invokes one o

2条回答
  •  忘掉有多难
    2020-12-09 11:01

    Here's the equivalent C# code for the code mentioned above

    string script = "function Test-Me($param1, $param2) { \"Hello from Test-Me with $param1, $param2\" }";
    
    using (var powershell = PowerShell.Create())
    {
        powershell.AddScript(script, false);
    
        powershell.Invoke();
    
        powershell.Commands.Clear();
    
        powershell.AddCommand("Test-Me").AddParameter("param1", 42).AddParameter("param2", "foo");
    
        var results = powershell.Invoke();
    }
    

提交回复
热议问题