1

我正在用 C# 编写 CmdLet 并使用Powershell-Class并调用不同的命令。这是我的代码:

PowerShell poswershell;
public Construcor()
{
     powershell = PowerShell.Create()
}
public Collection<PSObject> InvokeRestMethod(string uri)
{
    return InvokePSCommand("Invoke-RestMethod", new[] { uri });
}

public Collection<PSObject> InvokePSCommand(string command, string[] args)
{
    var execute = command;
    execute = GetExecuteCommand(args, execute);
    powershell.Commands.AddScript(execute);
    return powershell.Invoke();

}

private static string GetExecuteCommand(string[] args, string execute)
{
    if (args == null) return execute;
    for (var i = 0; i < args.Count(); i++)
    {
        execute += " " + args[i];
    }
    return execute;
}

它像我想要的那样工作,但真的很慢。我想要同样的功能,这给了我一个Collection<PSObject>支持。但是当我InvokeRestMehtod多次调用时,需要很长时间才能解决这个问题。为什么我只是为了一个简单的问题而使用它WebRequest?答案是,我必须从 uri(返回json)中读取一些信息。事实上,json结构总是不同的。因此,Invoke-RestMehtod这正是我所需要的,一个动态对象(PSObject)。我必须拥有这种对象,因为在该过程之后,我需要将其返回给 powershell 用户,以便他可以通过管道传输对象并进一步使用它。我现在的问题是,我怎样才能从返回的 uri 中获得相同的结果,我可以将其传递到 powershell 中json

编辑

我找到了这个 dll=> Microsoft.PowerShell.Commands.Utility.dll,它在C#代码中包含InvokeRestMethod-CmdLet 由powershell. 如果我能很好地阅读这段代码,我可以(会)在我的代码中使用它。然后我不会创建一个 PowerShell 实例并从我的 powershell-CmdLet 调用另一个 CmdLet,我不太喜欢它并且需要很长时间。有人知道这一点dll并且可以帮助我为我的项目自定义此代码吗?

我找到了dottrace并分析了这个过程,这里有一个截图我无法从中得到任何有用的信息,也许你们中的某个人?但我很确定Powershell.Invoke()在执行时会花费大部分时间。

4

2 回答 2

2

为什么不重复使用相同的 PowerShell 对象,而不是每次都创建一个新对象?每次实例化都会导致 PowerShell 必须再次初始化。请务必在 Invoke() 调用之间调用 powershell.Commands.Clear() 。

于 2013-11-07T17:07:46.580 回答
0

我现在解决了这个问题,这里是读取 uri(返回JSON)并返回的基本代码object

  private object InvokeRest(string uri)
    {
        return InvokeRest(uri, null);
    }
    private object InvokeRest(string uri, NetworkCredential networkCredential)
    {
        var webRequest = WebRequest.Create(uri);
        if (networkCredential!=null)
            webRequest.Credentials = networkCredential;
        _webResponse = webRequest.GetResponse();
        var streamReader = new StreamReader(_webResponse.GetResponseStream());
        var str = streamReader.ReadToEnd();
        ErrorRecord exRef;
        var doc = JsonObject.ConvertFromJson(str, out exRef);
        return doc;
    }

因为我发现object你在powershell中输出的每一个,都转换成aPSObject并格式化它。

于 2013-11-11T11:55:30.233 回答