gpt4 book ai didi

c# - 从 c# 调用 powershell 函数的问题

转载 作者:太空狗 更新时间:2023-10-29 22:33:59 25 4
gpt4 key购买 nike

我正在尝试调用 powershell 文件中的函数,如下所示:

    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 中:

Function BatAvg
{
param ($Name, $Runs, $Outs)
$Avg = [int]($Runs / $Outs*100)/100
Write-Output "$Name's Average = $Avg, $Runs, $Outs "
}

我收到以下异常:

术语“BatAvg”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。

我做错了什么,我承认,我对 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# - 从 c# 调用 powershell 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com