简体   繁体   English

如何从运行Powershell脚本读取返回的值

[英]how to read the returned values from running a powershell script

I am work on an asp.net mvc web application and i am calling powershell scripts inside my web application, as follow:- 我正在asp.net mvc Web应用程序上工作,并且正在Web应用程序内调用Powershell脚本,如下所示:

var shell = PowerShell.Create();

string PsCmd = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;

PsCmd = PsCmd + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;

PsCmd = PsCmd + "Get-VMHost " + System.Environment.NewLine;  

shell.Commands.AddScript(PsCmd);

var results = shell.Invoke();

now I will get the following values :- 现在我将获得以下值:

在此处输入图片说明

so can anyone adivce how i can access values such as Build, or loop thorugh thr NetworkInfo ? 所以任何人都可以提出我如何访问Build等值或通过NetworkInfo循环访问? thanks EDIT full trace picture:- 谢谢编辑完整的跟踪图片:- 在此处输入图片说明

With dynamic keyword, you wouldn't have to know the strong type of one object. 使用dynamic关键字,您不必知道一个对象的强类型。 In fact, without having to know the type in advance, you can use this as you expected: a variable can be anything . 实际上,无需事先知道类型,就可以按预期使用它: 变量可以是any

For example, I could declare a method like this: 例如,我可以声明这样的方法:

    static void DynamicTest(dynamic arg)
    {
        Console.WriteLine(arg.aaa);
    }

DynamicTest accessed aaa field(or property) in arg without knowing that whether arg itself has aaa or not. DynamicTest在不知道arg本身是否具有aaa情况下访问了arg aaa字段(或属性)。 Using a dynamic means that you don't want compiler to detect the possible errors that you may or may not access something from a variable that does not actually have it. 使用dynamic意味着您不希望编译器检测可能会或可能不会从实际上没有变量的变量访问某些内容的错误。

You can call this method with: 您可以使用以下方法调用此方法:

DynamicTest(new {aaa = "I am accessible"});

it'll run, also you can call this method with: 它会运行,您也可以使用以下方法调用此方法:

DynamicTest(1); // I will cause runtime exception

So, in your specific situation, you could define the variable result as dynamic since you now know that you'll get a variable that contains several properties that you want to use. 因此,在您的特定情况下,您可以将变量result定义为动态,因为您现在知道将获得一个包含要使用的多个属性的变量。

var res = shell.Invoke()[0];
dynamic obj = res.BaseObject;

Therefore you can use it like a regular variable(without IntelliSense of course). 因此,您可以像使用常规变量一样使用它(当然不需要IntelliSense)。

Console.WriteLine(obj.Build); // Now I can compile yay!

Here. 这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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