Restart Hyper V machine using powershell cmdlet from C#

蹲街弑〆低调 提交于 2019-12-24 00:29:13

问题


I'm trying to build an app to restart VMs in Hyper V in Server 2012 I had each VM in the list restarting but i want to adapt it to turn the machine off and then back on. The commented code is the working forced resart. Thanks in advance.

public async static void RestartAllVMs(List<VM> vmList, int timeDelay)
    {
        PowerShell ps = PowerShell.Create();
        foreach (VM vm in vmList)
        {
            /*//Create PowerShell object
            PowerShell ps = PowerShell.Create();
            ps.AddCommand("Restart-VM");
            ps.AddArgument(vm.vmName);
            ps.AddParameter("Force");
            ps.Invoke();
            await Task.Delay(timeDelay * 1000);*/

            //Create PowerShell object
            //I want to run from here down instead of just restarting the code doesn't work and no errors are thrown.
            ps.AddCommand("Stop-VM");
            ps.AddArgument(vm.vmName);
            ps.AddCommand("Start-Sleep");
            ps.AddParameter("s", 10);



            ps.AddCommand("Start-VM");
            ps.AddArgument(vm.vmName);
            ps.AddCommand("Start-Sleep");
            ps.AddParameter("m", 500);
            ps.Invoke();
            await Task.Delay(timeDelay * 1000);

        }

    }

回答1:


Just in case you still need an answer:

using (PowerShell shell = PowerShell.Create())

before you start

shell.AddScript("Invoke-Command -ComputerName "name of your target PC" -ScriptBlock {Stop-VM " + VM.getname() + "}");

Stopps the VM and waits for result

shell.AddScript("Invoke-Command -ComputerName "name of your target PC" -ScriptBlock {Start-VM " + VM.getname() + "}");

Starts the VM and waits for result

foreach (PSObject outputItem in shell.Invoke())
{
    string name = outputItem.Members["Name"].Value.ToString()
}

Runs through all Machines and returns in this case the Name of your machine into string name, but it can return every parameter of the engine. (in this case string will only have the name of the last machine because it gets constantly rewritten but it should be no problem to replace it with your containing object.)

shell.Streams.Error
shell.Streams.Warning

returning all problems from powershell.

Hope that helps.

PS: Make sure that you have an up to date powershell, since many systems have older ones, that don't support all the commands, Also maybe there is an restart command, but I don't know and since I can't test it where I am, you need to find that for yourself.



来源:https://stackoverflow.com/questions/38839993/restart-hyper-v-machine-using-powershell-cmdlet-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!