1. 启动
$hostServer = "shlihu-2k8r2";
$vmName="Win7-Pro2";
function GetImageState
{
param
(
[string]$image = $(throw "param -image is required."),
[string]$hostServer = $(throw "param -hostserver is required.")
)
$virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer;
foreach ($virtualMachine in $virtualMachines)
{
if ($image -ieq $virtualMachine.ElementName)
{
return $virtualMachine.EnabledState;
}
}
throw "Cannot get the state of image [$image] on host server [$hostServer]";
}
function WaitImageToState
{
param
(
[string]$image = $(throw "param -image is required."),
[string]$hostServer = $(throw "param -hostserver is required."),
[int]$state = $(throw "param -$state is required."),
[int]$timeOut = $(throw "param -$timeOut is required.")
)
do
{
$timeOut = $timeOut - 5;
sleep (5);
$currentState = GetImageState -image:$image -hostserver:$hostServer;
if ($currentState -eq $state)
{
return;
}
if ($timeOut -le 0)
{
throw "Wait for image [$image] to state [$state] time out.";
}
}while($true);
}
"Start up the virtual machine..." + $hostServer
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
$virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer;
$virtualMachineRun = 2;
foreach ($virtualMachine in $virtualMachines)
{
if($virtualMachine.ElementName -eq $vmName)