问题调用从C#一个PowerShell功能 [英] Problem with calling a powershell function from c#
本文介绍了问题调用从C#一个PowerShell功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图调用一个函数在PowerShell中的文件如下:
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());
}
}
}
PowerShell的功能在CallPS名为.ps1:
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 "
}
我得到了以下异常:
术语BatAvg'未被识别为cmdlet,函数,脚本文件或可操作的程序的名称。
The term 'BatAvg' is not recognized as the name of a cmdlet, function, script file, or operable program.
我在做什么错了,我承认,我所知甚少关于PowerShell的
What am I doing wrong, I admit, I know very little about PowerShell.
推荐答案
这似乎为我工作:
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);
}
}
这篇关于问题调用从C#一个PowerShell功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文