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\");
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);
}
}
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.").
As it seems the Runspace
need to be connected to a Powershell
to make that work - see the sample code at MSDN.