Reputation:
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);
}
}
Upvotes: 3
Views: 709
Reputation: 208
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.
Upvotes: 2