Home > OS >  Get Virtual Machine names in PowerShell via C# (Hyper-V)
Get Virtual Machine names in PowerShell via C# (Hyper-V)

Time:11-16

I am trying to get the list of virtual machine names, from a local Hyper-V server, with the following code:

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.

I would like to get a result like the following output we get in 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

CodePudding user response:

Get-VM only works in a PowerShell session run as administrator. When I try your C# code run as an administrator it does print VM names.

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. 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.

(Another consideration, if the Hyper-V module is not being autoloaded you may need Import Hyper-V; at the beginning of your PowerShell code).

  • Related