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
This code is just a general idea and you will need to modify it to meet your needs, but in short, you basically need to. . .
Get the location where Hyper-V is setup to store VHD and VHDX files
You need to collect the full path name of each of those files
You then need to query each VM for each of it's hard disks and get the full path name to those files as well
You then need a method to compare those 2 collections of objects to one another and see which one is "not accounted for"
DO NOT DELETE FILES WITHOUT CONFIRMING IT IS SAFE
$VirtualHardDiskPath = Get-VMHost | Select-Object -ExpandProperty VirtualHardDiskPath
$FilesInUse = Get-VM | Select-Object -ExpandProperty HardDrives | Select-Object -ExpandProperty Path
$Allfiles = Get-ChildItem $VirtualHardDiskPath -Recurse | Select-Object -ExpandProperty FullName
$PotentialOrphan = Compare-Object -ReferenceObject $Allfiles -DifferenceObject $FilesInUse -IncludeEqual -PassThru | Where-Object {$_.SideIndicator -eq "<="}
Write-Warning -Message "The $PotentialOrphan file may be an orphaned file"
This is just a starting point. You would also need to consider whether or not the Hyper-V server is in a cluster. if so make the script run so that it checks all of the nodes in the cluster.