Posted in
Virtual Machine Manager,
Windows Powershell,
Windows Server |
3 Comments | 3,061 views | 09/06/2014 01:19
Sometimes, you may need to empty your CSV volume for a maintenance operation or due to a volume corruption.
So you can use this script if you need to drain all virtual machines and virtual disks from a CSV.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| # Target Volume
$TargetVolume = "Volume8"
# Get Cluster Nodes
$ClusterNodes = Get-Cluster | Get-ClusterNode
foreach ($ClusterNode in $ClusterNodes)
{
# Clear Variables
$VMs = $Null;
# Get All Virtual Machines on Target Volume
$VMs = Get-VM -ComputerName "$ClusterNode" | Where ConfigurationLocation -like "C:\ClusterStorage\$TargetVolume*"
foreach ($VM in $VMs)
{
# Get VM Information
$VMName = $VM.Name
Write-Host " "
Write-Host "Working on $VMName .."
Write-Host "Hyper-V Host: $ClusterNode"
# Get Volume Information
$Volume = ((Get-ClusterSharedVolume | Where {$_.SharedVolumeInfo.FriendlyVolumeName -notlike "*$TargetVolume*"} | Select -ExpandProperty SharedVolumeInfo | Select @{label="Name";expression={(($_.FriendlyVolumeName).Split("\"))[-1]}},@{label="FreeSpace";expression={($_ | Select -Expand Partition).FreeSpace}} | Sort FreeSpace -Descending)[0]).Name
# Move Virtual Machine
Move-VMStorage -ComputerName "$ClusterNode" -VMName "$VMName" -DestinationStoragePath "C:\ClusterStorage\$Volume\$VMName"
Write-Host "Done."
}
} |
# Target Volume
$TargetVolume = "Volume8"
# Get Cluster Nodes
$ClusterNodes = Get-Cluster | Get-ClusterNode
foreach ($ClusterNode in $ClusterNodes)
{
# Clear Variables
$VMs = $Null;
# Get All Virtual Machines on Target Volume
$VMs = Get-VM -ComputerName "$ClusterNode" | Where ConfigurationLocation -like "C:\ClusterStorage\$TargetVolume*"
foreach ($VM in $VMs)
{
# Get VM Information
$VMName = $VM.Name
Write-Host " "
Write-Host "Working on $VMName .."
Write-Host "Hyper-V Host: $ClusterNode"
# Get Volume Information
$Volume = ((Get-ClusterSharedVolume | Where {$_.SharedVolumeInfo.FriendlyVolumeName -notlike "*$TargetVolume*"} | Select -ExpandProperty SharedVolumeInfo | Select @{label="Name";expression={(($_.FriendlyVolumeName).Split("\"))[-1]}},@{label="FreeSpace";expression={($_ | Select -Expand Partition).FreeSpace}} | Sort FreeSpace -Descending)[0]).Name
# Move Virtual Machine
Move-VMStorage -ComputerName "$ClusterNode" -VMName "$VMName" -DestinationStoragePath "C:\ClusterStorage\$Volume\$VMName"
Write-Host "Done."
}
}
That will move all virtual machines via Storage Live Migration into best available CSV volume.