Forum Discussion
JNichk323
Dec 19, 2024Copper Contributor
Hyper-V orphaned or unnecceasry file script
I am trying to create a script that I can run against a Hyper-V cluster or host that can scan and identify orphaned files or files that are unused. THe idea is to clean up a cluster that has a lot o...
Vern_Anderson
Jan 03, 2025Copper Contributor
You would first need to determine if the Hypervisor(s) are clustered or stand alone servers.
You would need to capture the default VM storage location from Hyper-V itself
You would need to do a recursive file search at that location for any files that might be VHD or VHDX files
Then for each of those files check every VM to see if that is attached as a drive
If no VM is using the file have the script do whatever you need to do. In my example I just have it write a warning that the drive is potentially orphaned. You need to manually be sure before you assume or delete any files but this script will at least show you files that are not attached to any VM.
Function Get-OrphanedVHD
{
Param ([Parameter(Mandatory=$true,Position=0)]$ComputerName)
$VirtualHardDiskPath = Get-VMHost -ComputerName $ComputerName | Select-Object -ExpandProperty VirtualHardDiskPath
$Files = Invoke-Command -ComputerName $ComputerName {Get-Childitem -Path $VirtualHardDiskPath -Recurse | Select-Object -ExpandProperty FullName}
foreach ($File in $Files)
{
$VMPath = Get-VM -ComputerName $ComputerName | ForEach-Object {Get-VHD -VMId $_.VMId -ComputerName $ComputerName | Where-Object {$_.Path -like $File}}
if ($VMPath) {Write-Verbose -Message "$VMPath is currently attached to a VM"}
else {Write-Warning -Message "The $File file is potentially an 'orphan'"}
}
}
$Nodes = Get-ClusterNode | Select-Object -ExpandProperty Name
if ($Nodes)
{
foreach ($Node in $Nodes)
{
Get-OrphanedVHD -ComputerName $Node
}
}
else
{
Get-OrphanedVHD -ComputerName $ENV:COMPUTERNAME | Select-Object -ExpandProperty VirtualHardDiskPath
}
You should also be concerned with orphaned checkpoints or snapshots. When I used to work with Hyper-V a lot more I had written a lot of scripts to do just this kind of maintenance. I don't currently have access to those files right now so I rewrote this from scratch ion kind of a hurry, so it should at least give you a starting point.
The backup software we used to use could sometimes leave orphaned checkpoints. it would be extremely difficult to delete them is the "chain" is missing a link. The checkpoints can not simply be merged unless all the files are there. So be careful about deleting things. Make sure no VMs have checkpoints before you proceed at your own risk!
JNichk323
Jan 03, 2025Copper Contributor
This is great Vern. Thank you for responding.