次の方法で共有


Removing a VHD From A VM Using The Hyper-V WMI V2 Namespace

What good would Attaching a VHD To A VM Using The Hyper-V WMI V2 Namespace be if you couldn’t remove one two… Here’s how you do it.

 

Removing a virtual hard disk

 $vmName = "Test" 
$vhdPath = "d:\vms\Test.vhdx"

#Retrieve the Hyper-V Management Service, ComputerSystem class for the VM and the VM’s SettingData class. 
$Msvm_VirtualSystemManagementService = Get-WmiObject -Namespace root\virtualization\v2 `
      -Class Msvm_VirtualSystemManagementService 

$Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 `
      -Class Msvm_ComputerSystem -Filter "ElementName='$vmName'" 

$Msvm_VirtualSystemSettingData = ($Msvm_ComputerSystem.GetRelated("Msvm_VirtualSystemSettingData", `
     "Msvm_SettingsDefineState", `
      $null, `
      $null, ` 
     "SettingData", `
     "ManagedElement", `
      $false, $null) | % {$_}) 

#Find the VirtualDisk with the path specified
$virtualHardDisk = $Msvm_VirtualSystemSettingData.GetRelated("Msvm_StorageAllocationSettingData") | Where-Object {
    ($_.HostResource -contains $vhdPath)} 

#Save the associated Disk Drive
$SyntheticDiskDrive = [WMI]$virtualHardDisk.Parent

#Call the RemoveResourceSettings function with the path to virtual hard disk
$Msvm_VirtualSystemManagementService.RemoveResourceSettings($virtualHardDisk)

#Call the RemoveResourceSettings function with the path to disk drive
$Msvm_VirtualSystemManagementService.RemoveResourceSettings($SyntheticDiskDrive)

-Taylor Brown

-Program Manager, Hyper-V

Comments

  • Anonymous
    June 25, 2015
    I'm guessing this script would be run on the server? Do you know how to do this in c# on a different computer which has connected via an admin account to the host server?