从Powershell命令到C#变量的输出结果 [英] Output Result from Powershell command to C# variable

查看:316
本文介绍了从Powershell命令到C#变量的输出结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#webforms应用程序中,我试图返回Hyper-V服务器上VM的当前分配的内存总量.我已经编写了powershell命令,并且我有一种行之有效的方法,可以远程连接到hyper-v服务器并运行脚本块.我将脚本添加为字符串,然后使用ps.addscript(scriptString);

Within a c# webforms application, I am trying to return the current assigned memory total for the VM's on our Hyper-V server. 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. I am adding the script as a string and then inserting it into the pipeline with ps.addscript(scriptString);

命令运行正常,应用程序中没有错误,但我不知道如何将结果值返回给c#变量(最好是int)

The command runs fine and there are no errors in the application but I do not know how to return the result value to a c# variable (preferably an int)

有关如何执行此操作的任何想法?不使用运行空间,但不知道是否必须这样做.我只想调用管道,然后将我的输出值添加到c#变量中.

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 a c# variable.

(出于本文的目的,我已用"1.1.1.1"替换了IP)

(I have replaced IPs with '1.1.1.1' for purposes of this post)

 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();

推荐答案

在脚本中,results变量是PSObject的集合.

In your script, the results variable is a collection of PSObject.

您可以对其进行迭代,并获取Powershell结果中每个列/属性"的值……类似:

You can iterate it and get the value for each of the "columns/properties" of the powershell result... something like:

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

每个PSObject上的字段取决于Powershell返回的对象的类型

The fields on each PSObject depend on the type of objects returned by Powershell

这篇关于从Powershell命令到C#变量的输出结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆