Powershell 操作hyper-v 一般性操作

本文档介绍了如何利用Powershell进行Hyper-V的常见操作,包括启动和关闭虚拟机,查看虚拟机状态,获取及恢复快照。通过这些步骤,可以高效地管理和维护Hyper-V环境。

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)
  {
   $result = $virtualMachine.RequestStateChange($virtualMachineRun);
   if ($result.ReturnValue -ne 4096)
   {
    throw "Failed to send start request to VM - " + $virtualMachine;
   }  
   WaitImageToState -image:$virtualMachine.ElementName -hostserver:$hostServer -state:$virtualMachineRun -timeOut:60;
  }
 }
 $vmName + "startup Finished!"


2.  关闭

 

$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);
 }
 
 "Shutdown the virtual machine..."
 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
 $virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer;
 $virtualMachineRun = 3;
 foreach ($virtualMachine in $virtualMachines)
 {
  if($virtualMachine.ElementName -eq $vmName)
  {
   $result = $virtualMachine.RequestStateChange($virtualMachineRun);
   if ($result.ReturnValue -ne 4096)
   {
    throw "Failed to send start request to VM - " + $virtualMachine;
   }  
   WaitImageToState -image:$virtualMachine.ElementName -hostserver:$hostServer -state:$virtualMachineRun -timeOut:60;
  }
 }
 $vmName + "Shutdown Finished!"


3. 获取虚拟机状态

$hostServer = "shlihu-2k8r2";
$vmName="Win7-Pro2";
$status = -1 
 $virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer 
 foreach ($virtualMachine in $virtualMachines)
 {
     if ($vmName -ieq $virtualMachine.ElementName)
     {
         $status = $virtualMachine.EnabledState
         break
     }
 }
 
 switch($status)
 {
     -1    {throw "Cannot get the state of vmName [$vmName] on host server [$hostServer]"}
     2     {"Running."}
     3     {"Closed."} 
     32768 {"Paused."} 
     32769 {"Saved."} 
     32770 {"Starting."} 
     32773 {"Saving."} 
     32774 {"Stopping."} 
     32776 {"Pausing."}
     32777 {"Restoring."} 
     default {"Unknow Status."}
 }


4. 获取snapshot列表

$hostServer = "shlihu-2k8r2";
$vmName="Win7-Pro2";

$virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer; 
 foreach ($virtualMachine in $virtualMachines) 
 {   
     if($virtualMachine.ElementName -eq $vmName)
     {
         # get snapshots of the virtual machine
         $queryStr = "SELECT * FROM Msvm_VirtualSystemSettingData WHERE SystemName='" + $virtualMachine.Name + "' and SettingType=5";
         $snapShots = Get-WmiObject -Query $queryStr -Namespace "root\virtualization" -ComputerName $hostServer;
 
         foreach ($aSnapShot in $snapShots)
         {
            $aSnapShot.ElementName
            [System.DateTime]::ParseExact($aSnapShot.CreationTime.Substring(0,14), "yyyyMMddHHmmss", $null).ToLocalTime().ToString()
            $aSnapShot.Notes
         }
     }
 }


5. 恢复snapshot

$hostServer = "shlihu-2k8r2";
$vmName="Win7-Pro2";
$snapshotName ="Win7-Pro2 -VS2010-Silk2010r2-Completed-Install"
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);
 }
 
 "Rollback the virtual machine..."
 $virtualMachines = Get-WmiObject -Class "MSVM_ComputerSystem" -Namespace "root\virtualization" -ComputerName $hostServer;
 $virtualSystemService = Get-WmiObject -Class "Msvm_VirtualSystemManagementService" -Namespace "root\virtualization" -ComputerName $hostServer;
 foreach ($virtualMachine in $virtualMachines)
 {   
  if($virtualMachine.ElementName -eq $vmName)
  {
   # get snapshot of the virtual machine
   $queryStr = "SELECT * FROM Msvm_VirtualSystemSettingData WHERE SystemName='" + $virtualMachine.Name + "' and SettingType=5";
   $snapShots = Get-WmiObject -Query $queryStr -Namespace "root\virtualization" -ComputerName $hostServer;
   foreach ($aSnapShot in $snapShots)
   {
    # revert to specified snapshot
    if ($aSnapShot.ElementName -ieq $snapshotName)
    {
     # apply snapshot
     $result = $virtualSystemService.ApplyVirtualSystemSnapShot($virtualMachine.__PATH, $aSnapShot.__PATH);
     if ($result.ReturnValue -ne 0)
     {
      throw "Failed to apply snapshot ["+$snapshotName+"] to VM ["+$image+"]";
     }       
     WaitImageToState -image:$virtualMachine.ElementName -hostserver:$hostServer -state:32769 -timeOut:120;
    }
   }
  }
 }
 "Finished rollback!"


 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值