简体   繁体   中英

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. 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 ac# 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 ac# 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();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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