Output Result from Powershell command to C# variable

倖福魔咒の 提交于 2020-05-16 00:57:29

问题


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

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)

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.

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

回答1:


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

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`
}

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




回答2:


You may want to try and take advantage of "dynamic" from the 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



来源:https://stackoverflow.com/questions/42365824/output-result-from-powershell-command-to-c-sharp-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!