gpt4 book ai didi

C# 使用预先创建的对象调用 Powershell

转载 作者:行者123 更新时间:2023-11-30 22:34:02 27 4
gpt4 key购买 nike

我刚开始使用 PS,正在编写一些我需要在 PS 中测试的 C# 类。

请注意,这些类不是 CmdLets。

我想做这样的事情:

var myCustomObj = new CustomObj { Message = "Hello world" };

var ps = Powershell.Create();

ps.AddCommand("Import-Module").AddParameter("Assembly", "MyCustomAsm");
ps.AddCommand("myCustomObj.Run()").AddParameter(myCustomObj);

foreach(string str in ps.AddCommand("Out-String").Invoke<string>())
Console.WriteLine(str);

我在传递给 PS 的对象上调用 Run(),结果将是打印输出“Hello world”。

但我什至不确定这是可能的(可能是出于安全原因)。

我想我有两个选择:

  1. 这是可能的。如果是这样,请帮助我:) ?

  2. 我必须根据现有对象生成脚本文件,然后执行“AddScript(...)”让 ps 执行它。

    <

任何让我开始的指示都很好 :)。

亲切的问候。

最佳答案

我找到了一个解决方案:

        var objs= new PSDataCollection<CustomObj> {obj};

using (var ps = PowerShell.Create())
{
ps.Runspace.SessionStateProxy.SetVariable("objList", objs);
ps.AddScript(@"$objList| ForEach { $_.Run()}");
ps.AddCommand("Out-String");
var output = ps.Invoke();

var stringBuilder = new StringBuilder();
foreach (var obj in output)
{
stringBuilder.AppendLine(obj.ToString());
}

var result = stringBuilder.ToString().Trim();

//Evaluate result.
}

关于C# 使用预先创建的对象调用 Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020635/

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