Problem with calling a powershell function from c#

后端 未结 3 2101
谎友^
谎友^ 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:20

    This seems to work for me:

    using (Runspace runspace = RunspaceFactory.CreateRunspace())
    {
        runspace.Open();
        PowerShell ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.AddScript(script);
        ps.Invoke();
        ps.AddCommand("BatAvg").AddParameters(new Dictionary<string, string>
        {
            {"Name" , "John"},
            {"Runs", "6996"},
            {"Outs","70"}
        });
    
        foreach (PSObject result in ps.Invoke())
        {
            Console.WriteLine(result);
        }
    }
    
    0 讨论(0)
  • 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<string, string>
    {
         {"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.").

    0 讨论(0)
  • As it seems the Runspace need to be connected to a Powershell to make that work - see the sample code at MSDN.

    0 讨论(0)
提交回复
热议问题