Problem with calling a powershell function from c#

后端 未结 3 2100
谎友^
谎友^ 2020-12-11 20:08

I\'m trying to call a function in a powershell file as follows:

    string script = System.IO.File.ReadAllText(@\"C:\\Users\\Bob\\Desktop\\CallPS.ps1\");

           


        
3条回答
  •  春和景丽
    2020-12-11 20:30

    The solution can be simplified further as in this case a non-default Runspace is not needed.

    var ps = PowerShell.Create();
    ps.AddScript(script);
    ps.Invoke();
    ps.AddCommand("BatAvg").AddParameters(new Dictionary
    {
         {"Name" , "John"}, {"Runs", "6996"}, {"Outs","70"}
    });
    foreach (var result in ps.Invoke())
    {
         Console.WriteLine(result);
    }
    

    One other pitfall would be to use AddScript(script, true) in order to use a local scope. The same exception would be encountered (i.e. "The term 'BatAvg' is not recognized as the name of a cmdlet, function, script file, or operable program.").

提交回复
热议问题