[英]Powershell addscript and invoke from C# not displaying result on command line
[英]Output Result from Powershell command to C# variable
在 ac# webforms 應用程序中,我試圖返回當前為我們的 Hyper-V 服務器上的虛擬機分配的內存總量。 我已經編寫了 powershell 命令,而且我有一種經過驗證的遠程連接到 hyper-v 服務器並運行腳本塊的方法。 我將腳本作為字符串添加,然后使用 ps.addscript(scriptString); 將其插入到管道中。
該命令運行良好,應用程序中沒有錯誤,但我不知道如何將結果值返回到 ac# 變量(最好是 int)
關於我如何做到這一點的任何想法? 不使用運行空間,但不知道我是否必須這樣做。 我只想調用管道,然后將我的輸出值添加到 ac# 變量。
(出於本文的目的,我已將 IP 替換為“1.1.1.1”)
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
的集合。
您可以迭代它並獲取 powershell 結果的每個“列/屬性”的值......類似於:
var results = ps.Invoke();
foreach (var psobject in results)
{
var myInteger = Convert.ToInt32(psobject.Members["SomeField"].Value);
// do something with `myInteger`
}
每個PSObject
上的字段取決於 Powershell 返回的對象類型
您可能想嘗試利用 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())
{
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.