简体   繁体   English

Powershell 命令的输出结果到 C# 变量

[英]Output Result from Powershell command to C# variable

Within ac# webforms application, I am trying to return the current assigned memory total for the VM's on our Hyper-V server.在 ac# webforms 应用程序中,我试图返回当前为我们的 Hyper-V 服务器上的虚拟机分配的内存总量。 I have written the powershell command and I have a proven way of remotely connecting to the hyper-v server and running a script block.我已经编写了 powershell 命令,而且我有一种经过验证的远程连接到 hyper-v 服务器并运行脚本块的方法。 I am adding the script as a string and then inserting it into the pipeline with ps.addscript(scriptString);我将脚本作为字符串添加,然后使用 ps.addscript(scriptString); 将其插入到管道中。

The command runs fine and there are no errors in the application but I do not know how to return the result value to ac# variable (preferably an int)该命令运行良好,应用程序中没有错误,但我不知道如何将结果值返回到 ac# 变量(最好是 int)

Any ideas on how I do this?关于我如何做到这一点的任何想法? Not using runspaces but don't know if I have to.不使用运行空间,但不知道我是否必须这样做。 I just want to invoke the pipeline and then add my output value to ac# variable.我只想调用管道,然后将我的输出值添加到 ac# 变量。

(I have replaced IPs with '1.1.1.1' for purposes of this post) (出于本文的目的,我已将 IP 替换为“1.1.1.1”)

 string breakLine = System.Environment.NewLine;

string getHyp1Use = "$hypUN = \"DOMAIN\\" + boxUN.Text + "\"" + breakLine +
    " $hypPWD =ConvertTo-SecureString \"" + boxPWD.Text + "\" -AsPlainText -Force" + breakLine +
    " $hypCREDS = New-Object System.Management.Automation.PSCredential($hypUN, $hypPWD)" + breakLine +
    " set-item wsman:\\localhost\\Client\\TrustedHosts -value 1.1.1.1 -force" + breakLine +
    " $builderSession = New-PSSession -ComputerName 1.1.1.1 -Credential $hypCREDS" + breakLine +
    " Invoke-Command -Session $builderSession -ScriptBlock {Get-VM | Where { $_.State –eq ‘Running’ } | measure MemoryAssigned -Sum | select -ExpandProperty Sum}" + breakLine +
    " Invoke-Command -ScriptBlock {Remove-PsSession -Session $builderSession}";

                string hyp1Use = null;
                PowerShell ps = PowerShell.Create();
                ps.AddScript(getHyp1Use);
                var results = ps.Invoke();

In your script, the results variable is a collection of PSObject .在您的脚本中, results变量是PSObject的集合。

You can iterate it and get the value for each of the "columns/properties" of the powershell result... something like:您可以迭代它并获取 powershell 结果的每个“列/属性”的值......类似于:

var results = ps.Invoke();
foreach (var psobject in results)
{
  var myInteger = Convert.ToInt32(psobject.Members["SomeField"].Value);
  // do something with `myInteger`
}

The fields on each PSObject depend on the type of objects returned by Powershell每个PSObject上的字段取决于 Powershell 返回的对象类型

You may want to try and take advantage of "dynamic" from the DLR.您可能想尝试利用 DLR 的“动态”。 Makes it far easier to work with.使它更容易使用。

static void Main(string[] args)
        {
            var script = "Get-Process | select -Property @{N='Name';E={$_.Name}},@{N='CPU';E={$_.CPU}}";

            var powerShell = PowerShell.Create().AddScript(script);

            foreach (dynamic item in powerShell.Invoke().ToList())
            {
                if (item.CPU > 10) //check if the CPU usage is greater than 10
                {
                    Console.WriteLine("The process greater than 10 CPU counts is : " + item.Name);
                }
            }

            Console.Read();
        }

Link: calling-c-code-in-powershell-and-vice-versa链接: calling-c-code-in-powershell-and-vice-versa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM