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