2017-02-21 112 views
1

在c#webforms应用程序中,我试图返回Hyper-V服务器上VM的当前分配内存总数。我已经编写了powershell命令,并且我有一种经过验证的方式,可以远程连接到hyper-v服务器并运行脚本块。我将脚本添加为字符串,然后使用ps.addscript(scriptString)将其插入到管道中;从Powershell命令到C#变量的输出结果

命令运行正常,并有在应用程序中没有错误,但我不知道怎么的结果值返回到C#变量(最好是一个int)

任何想法我如何做到这一点?不使用运行空间,但不知道是否必须。我只想调用管道,然后将我的输出值添加到c#变量中。

(我已经取代与这篇文章的目的, '1.1.1.1' IPS)

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

回答

1

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

可以遍历并获得价值为每个PowerShell的结果的“列/属性”的......是这样的:

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

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

1

您可能想尝试利用DLR中的“动态”。使它更容易处理。

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()) 
      { 
       //check if the CPU usage is greater than 10 
       if (item.CPU > 10) 
       { 
        Console.WriteLine("The process greater than 10 CPU counts is : " + item.Name); 
       } 
      } 

      Console.Read(); 
     } 

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