简体   繁体   English

通过 C# (Hyper-V) 在 PowerShell 中获取虚拟机名称

[英]Get Virtual Machine names in PowerShell via C# (Hyper-V)

I am trying to get the list of virtual machine names, from a local Hyper-V server, with the following code:我正在尝试使用以下代码从本地 Hyper-V 服务器获取虚拟机名称列表:

string _scr = ("Get-VM | Select -ExpandProperty Name");
var _ps = PowerShell.Create();
_ps.AddScript(_scr);
Collection<PSObject> _cObj = _ps.Invoke();
foreach (PSObject _vm in _cObj)
{
    Console.WriteLine(_vm);
}

The Get-VM cmdlet should return values in string format already, but I don't get any output. Get-VM cmdlet 应该已经以字符串格式返回值,但我没有得到任何输出。

I would like to get a result like the following output we get in PowerShell:我想得到类似于我们在 PowerShell 中得到的以下输出的结果:

PS C:\> Get-VM | Select -ExpandProperty Name
VM-Name1
VM-Name2
VM-Name3
VM-Name4
PS C:\>

Can anyone help me with this please?任何人都可以帮我解决这个问题吗?

Thanks a million.太感谢了。

Ada艾达

Get-VM only works in a PowerShell session run as administrator. Get-VM 仅适用于以管理员身份运行的 PowerShell 会话。 When I try your C# code run as an administrator it does print VM names.当我尝试以管理员身份运行您的 C# 代码时,它确实会打印 VM 名称。

When I try it without administrator rights I get no output, same as you - but there is an error reported if you check _ps.HadErrors it's true .当我在没有管理员权限的情况下尝试时,我没有任何输出,与您一样 - 但是如果您检查_ps.HadErrors it _ps.HadErrors true _ps.HadErrors报告错误。 Try this version of your code:试试这个版本的代码:

string _scr = ("Get-VM | Select -ExpandProperty Name");
var _ps = PowerShell.Create();
_ps.AddScript(_scr);
Collection<PSObject> _cObj = _ps.Invoke();

if (_ps.HadErrors) {
    Console.WriteLine(_ps.Streams.Error[0].ToString());
}

foreach (PSObject _vm in _cObj)
{
    Console.WriteLine(_vm);
}

I get "You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer {name}", you may get another error which gives you an idea what is going wrong.我收到“您没有完成此任务所需的权限。请联系计算机 {name} 的授权策略管理员”,您可能会收到另一个错误消息,让您知道发生了什么问题。

(Another consideration, if the Hyper-V module is not being autoloaded you may need Import Hyper-V; at the beginning of your PowerShell code). (另一个考虑因素,如果 Hyper-V 模块未自动加载,您可能需要Import Hyper-V;在 PowerShell 代码的开头)。

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

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