Powershell 脚本总是 return 零结果。如果我从 Powershell window 调用相同的脚本,它会很好地工作

Powershell scripts will always return zero result. while the same script will work well if i call it from the Powershell window

我已经在 ym 应用程序服务器中安装了 VMware PowerCLI,如果我直接在 windows powershell 中编写以下内容,我将得到我正在寻找的结果:-

PS C:\Windows\system32> add-pssnapin VMware.VimAutomation.Core;
PS C:\Windows\system32> Connect-VIServer -Server ***** -User root -Password "*******"
PS C:\Windows\system32> Get-VMHOST

Name                 ConnectionState PowerState NumCpu CpuUsageMhz CpuTotalMhz   MemoryUsageGB   MemoryTotalGB Version
----                 --------------- ---------- ------ ----------- -----------   -------------   ------------- -------
**********           Connected       PoweredOn       8        2733       18400          12.894          15.998   5.0.0

但是如果我尝试 运行 我的 asp.net mvc visual studio 项目中的命令,如下所示:-

 public ActionResult About(string vCenterIp = "****", string vCenterUsername = "****", string vCenterPassword = "****")
        {


var shell = PowerShell.Create();



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



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


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



                shell.Commands.AddScript(PsCmd);

                var results = shell.Invoke();




                if (results.Count > 0)

那么结果将始终为零..有人可以就此提出建议吗?

如果将它们吸收到 Powershell 局部变量中而不传递到管道,怎么会有结果? "$VMHosts = Get-VMHost" 此命令不return 任何东西(Get-VMHost 被吸收)。改成普通的Get-VMHost就会有结果