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");
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline(script))
{
Command c = new Command("BatAvg",false);
c.Parameters.Add("Name", "John");
c.Parameters.Add("Runs", "6996");
c.Parameters.Add("Outs", "70");
pipeline.Commands.Add(c);
Collection<PSObject> results = pipeline.Invoke();
foreach (PSObject obj in results)
{
// do somethingConsole.WriteLine(obj.ToString());
}
}
}
The powershell function is in CallPS.ps1:
Function BatAvg
{
param ($Name, $Runs, $Outs)
$Avg = [int]($Runs / $Outs*100)/100
Write-Output "$Name's Average = $Avg, $Runs, $Outs "
}
I'm getting the following exception:
The term 'BatAvg' is not recognized as the name of a cmdlet, function, script file, or operable program.
What am I doing wrong, I admit, I know very little about PowerShell.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With