Click here to Skip to main content
15,886,793 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I am trying to get the list of virtual machine names, from a local Hyper-V server, with the following code:

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

What I have tried:

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
Posted
Updated 17-Dec-21 4:30am

1 solution

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:

PowerShell
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).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900